使用mysql官方python驱动
mysql驱动官网下载 安然安装即可
注意
pycharm 创建项目勾选上从全局加载 inherit global site-packages
使用模块
import mysql.connector
创建数据库连接
config = {
"host": "xxxx",
"port": "3306",
"user": "xxxx",
"password": "xxxx",
"database": "sun_riches_test",
"autocommit": True
}
con = mysql.connector.connect(**config)
创建游标
cursor = con.cursor()
执行sql语句
cursor.execute("select name,nickname from admin_users limit 5")
result = cursor.fetchall()
关闭连接
con.close()
事务
try:
con.start_transaction()
cursor.execute("update admin_users set name = 'zsf2' where id = 14")
con.commit()
except Exception as e:
print(e)
if "con" in dir():
con.rollback()
finally:
if "con" in dir():
con.close()
注意事项
cursor 中的结果要全部取尽才能进行下一个
cursor.execute()
|