python使用pymysql操作数据库

pymysql连接数据库

连接数据库,进行增删改查操作

import pymysql

stg_db_conf = {'host':'host地址','user':'用户名','passwd':'密码'}
lxkdb = pymysql.connect(**stg_db_conf ,database='lxk', charset='utf8')

lxk_cursor = lxkdb.cursor()

## 这样写存在安全问题,会出现sql注入情况
# sql_query = 'select * from user where username = %s'%('abc')
# lxk_cursor.execute(sql_query)
sql_query = 'select * from user where username = %s'
lxk_cursor.execute(sql_query,('abc'))
result = lxk_cursor.fetchone()
print(result)
print(bool(result))

其中,result = lxk_cursor.fetchone()返回对应查询的数据库结果,可打印出结果,检查是否是想查询的内容
查询时,避免使用字符串格式化,优化为在sql执行时,将对应的实参传入进去
row_1 = cursor.fetchone()# 获取单条查询数据
row_2 = cursor.fetchmany(3)# 可以获取指定数量的数据
row_3 = cursor.fetchall()# 获取多条查询数据

posted @ 2021-10-18 21:24  happy-winds  阅读(135)  评论(0编辑  收藏  举报