PyMysql连接数据库
防止sql注入
import pymysql
def insertsql():
# 建立连接
connection_sql = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='mysql',
db='xiaoshuobase',
charset='utf8'
)
# 获取游标
cursor = connection_sql.cursor(pymysql.cursors.DictCursor)
str = '1'
# str2 = '18'
sql = 'select * from book where id >%s '
# sql = 'select name,age,gender,cls_id from students where id >%s and age > %s'
print(sql)
# 尝试执行代码
try:
cursor.execute(sql, str)
# cursor.execute(sql, [str,str2])
# 获取查询所有的数据
a = cursor.fetchall()
print(a)
connection_sql.commit()
# try中代码有错误进入这里
except Exception as e:
connection_sql.rollback()
raise e
#try里面的代码没有问题进入这里