pymysql模块是第三方模块,提供了python连接并操作MySQL数据库的功能
pymysql操作数据库增删改查
import pymysql
# 创建一个conn对象
conn = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="123456",
database="test",
charset="utf8"
)
# 创建一个cursor对象
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 新增一条数据
sql = "Insert into user(username,password) values (%(username)s,%(password)s)"
# 执行SQL语句
cursor.execute(sql,{"username":"surpass","password":"123!@#"})
conn.commit()
conn.close()
# 查询一条数据
sql = "Select username,password from user where id = 1"
cursor.execute(sql)
print(cursor.fetchall())
# 更新一条数据
sql = "Update user set password=%(password)s where id=3"
cursor.execute(sql,{"password":"123surpass"})
conn.commit()
# 删除一条数据
sql = "DELETE FROM user WHERE id = 3"
cursor.execute(sql)
conn.commit()
pymysql开启事务
try:
cursor.execute(sql_1)
cursor.execute(sql_2)
cursor.execute(sql_3)
except Exception as e:
connect.rollback() # 事务回滚
print('事务处理失败', e)
else:
connect.commit() # 事务提交
print('事务处理成功', cursor.rowcount)# 关闭连接
cursor.close()
connect.close()
数据库连接池
python编程中可以使用MySQLdb进行数据库的连接及诸如查询/插入/更新等操作,但是每次连接mysql数据库请求时,都是独立的去请求访问,相当浪费资源,而且访问数量达到一定数量时,对mysql的性能会产生较大的影响。因此,实际使用中,通常会使用数据库的连接池技术,来访问数据库达到资源复用的目的。
"""
数据库连接池
"""
import pymysql
from DBUtils.PooledDB import PooledDB, SharedDBConnection
class MysqlPool:
def __new__(cls, *args, **kwargs):
"""
开启单例模式
"""
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self):
self.POOL = PooledDB(
creator=pymysql, # 使用连接数据库的模块
maxconnections=6, # 连接池允许最大的连接数,0和None表示不做限制
mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
maxcached=5, # 链接池中最多闲置的链接,0和None不限制
maxshared=0,
blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待
maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制
setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
ping=0,
# ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
host='127.0.0.1',
port=3306,
user='root',
password='123456',
database='test',
charset='utf8'
)
def __enter__(self):
"""
创建连接对象conn
创建游标对象cursor
"""
self.conn = self.POOL.connection()
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
关闭游标对象cursor
放回连接对象conn
"""
self.cursor.close()
self.conn.close()
def get_insert_id(self):
"""
获取当前连接最后一次插入操作生成的id,如果没有则为0
"""
self.cursor.execute("SELECT @@IDENTITY AS id")
res = self.cursor.fetchall()
return res[0]['id']
@classmethod
def fetch_one(cls, sql, param=None):
"""
@summary: 执行查询,并取出第一条
@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来
@param param: 可选参数,条件列表值(元组/列表)
"""
with cls() as SQLObject:
if param is None:
effect_row = SQLObject.cursor.execute(sql)
else:
effect_row = SQLObject.cursor.execute(sql, param)
return SQLObject.cursor.fetchone() if effect_row > 0 else False
@classmethod
def fetch_all(cls, sql, param=None):
"""
@summary: 执行查询,并取出所有结果集
@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来
@param param: 可选参数,条件列表值(元组/列表)
"""
with cls() as SQLObject:
if param is None:
effect_row = SQLObject.cursor.execute(sql)
else:
effect_row = SQLObject.cursor.execute(sql, param)
return SQLObject.cursor.fetchall() if effect_row > 0 else False
@classmethod
def fetch_many(cls, sql, num, param=None):
"""
@summary: 执行查询,并取出num条结果
@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来
@param num:取得的结果条数
@param param: 可选参数,条件列表值(元组/列表
"""
with cls() as SQLObject:
if param is None:
effect_row = SQLObject.cursor.execute(sql)
else:
effect_row = SQLObject.cursor.execute(sql, param)
return SQLObject.cursor.fetchmany(num) if effect_row > 0 else False
@classmethod
def insert_one(cls, sql, value):
"""
@summary: 向数据表插入一条记录
@param sql:要插入的SQL格式
@param value:要插入的记录数据tuple/list
@return: insertId 受影响的行数
"""
with cls() as SQLObject:
SQLObject.cursor.execute(sql, value)
SQLObject.conn.commit()
effect_row = SQLObject.get_insert_id()
return effect_row
@classmethod
def insert_many(cls, sql, values):
"""
@summary: 向数据表插入多条记录
@param sql:要插入的SQL格式
@param values:要插入的记录数据tuple(tuple)/list[list]
@return: count 受影响的行数
"""
with cls() as SQLObject:
count = SQLObject.cursor.executemany(sql, values)
SQLObject.conn.commit()
return count
@classmethod
def query(cls, sql, param=None):
with cls() as SQLObject:
if param is None:
count = SQLObject.cursor.execute(sql)
else:
count = SQLObject.cursor.execute(sql, param)
return count
@classmethod
def update(cls, sql, param=None):
"""
@summary: 更新数据表记录
@param sql: SQL格式及条件,使用(%s,%s)
@param param: 要更新的 值 tuple/list
@return: count 受影响的行数
"""
return cls.query(sql, param)
@classmethod
def delete(cls, sql, param=None):
"""
@summary: 删除数据表记录
@param sql: SQL格式及条件,使用(%s,%s)
@param param: 要删除的条件 值 tuple/list
@return: count 受影响的行数
"""
return cls.query(sql, param)
def begin(self):
"""
@summary: 开启事务
"""
self.conn.autocommit(0)
def end(self, option='commit'):
"""
@summary: 结束事务
"""
if option == 'commit':
self.conn.commit()
else:
self.conn.rollback()
def dispose(self, isEnd=1):
"""
@summary: 释放连接池资源
"""
if isEnd == 1:
self.end('commit')
else:
self.end('rollback')
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
m = MysqlPool()
# data = m.fetch_one("select * From user where username = %s",("surpass",))
# data=m.insert_one("insert into user(username,password) values (%s,%s)",("wl","123456"))
data = m.insert_many("insert into user(username,password) values (%s,%s)", [('xx', '123'), ('ll', '456')])
print(data)