Python操作MySQL
安装:
pip install pymysql
使用:
import pymysql
(1) 链接MySQL数据库
db = pymysql.connect(主机名,用户名,密码,数据库名)
db = pymysql.connect(host='localhost', user='root', password='123456', database='test')
(2) 设置字符集
db.set_charset('utf8')
(3) 创建游标对象
cursor = db.cursor()
(4) 执行SQL语句
cursor.execute(sql语句)
(5) 获取结果集
获取所有
cursor.fetchall()
获取一条
cursor.fetchone()
(6) 获取受影响的行数
cursor.rowcount
(7) 事物
实例:
try: sql = 'insert into user values(null,1,"张三",100,"二年级","一班")' print(sql) cursor.execute(sql) db.commit() except: db.rollback()
对于支持事务的数据库, 在Python数据库编程中,当游标建立之时,就自动开始了一个隐形的数据库事务。
commit()方法游标的所有更新操作,rollback()方法回滚当前游标的所有操作。每一个方法都开始了一个新的事务。
(8) 关闭数据库连接
db.close()
print("select name,password from user where name=\""+username+"\"") print("select name,password from user where name='"+username+"'") print("select name,password from user where name='%s'"%(username)) print("select name,password from user where name='{}'".format(username)) print(f"select name,password from user where name='{username}'")
MySQL数据库连接池
# 创建连接池: 最多20连接 POOL = PooledDB( creator=pymysql, maxconnections=20, mincached=2, blocking=True, host="127.0.0.1", port=3306, user="root", passwd="root123", charset="utf8", db='test' )
# 连接MySQL,去连接池中获取一个连接
conn = POOL.connection()
cursor = conn.cursor(cursor=DictCursor)
# 查询
cursor.execute("select id,username from info where username=%s and password=%s", [username, password])
row_dict = cursor.fetchone()
# 归还到连接池
cursor.close()
conn.close()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)