下载
pip install pymysql
连接数据库并执行sql
def executeSql(sql):
db = pymysql.connect(host=ip,port=3306,user=user,password=pwd,db=database,charset='utf8')
cursor = db.cursor()
try:
res=cursor.execute(sql)
except Exception as e:
print("执行失败:", e)
else:
print("执行成功")
db.close()
execute()进行sql语句过滤
sql = "select * from d1 where name = %s and id = %s"
cursor.execute(sql,(username, id))
批量执行
data=((1,2,3),
(4,5,6),
(7,8,9))
sql="insert into d1 (v1,v2,v3) values (%s,%s,%s)"
try:
cursor.executemany(sql,data)
db.commit()
except:
db.rollback()
事务处理(主要用于增删改)
try:
cursor.execute(sql, ('lxxx', '1234'))
db.commit()
except Exception as e:
db.rollback()
查询
res=cursor.execute(sql)
print(cur.fetchone())
print(cur.fetchmany(4))
info=cur.fetchall()