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) 事物

pymysql默认开启了事物处理 所以在添加数据的时候 需要commit 或者rollback

实例:

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()

(9) 拼凑正常完整的sql语句

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}'")

(9) 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()

复制代码

 

posted @   星尘yuan  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示