python操作数据库
Posted longlinji
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作数据库相关的知识,希望对你有一定的参考价值。
1.mysql操作
1 import pymysql 2 from DBUtils.PooledDB import PooledDB 3 4 5 class SQLHandler(object): 6 def __init__(self, host, port, db_username, db_password, db_name): 7 # pip install --default-timeout=100 dbutils 8 self.pool = PooledDB( 9 # 使用链接数据库的模块import pymysql 10 creator=pymysql, 11 # 连接池允许的最大连接数,0和None表示不限制连接数 12 maxconnections=6, 13 # 初始化时,链接池中至少创建的空闲的链接,0表示不创建 14 mincached=2, 15 # 链接池中最多闲置的链接,0和None不限制 16 maxcached=5, 17 # 链接池中最多共享的链接数量,0和None表示全部共享。 18 # 因为pymysql和MySQLdb等模块的 threadsafety都为1, 19 # 所有值无论设置为多少,maxcached永远为0,所以永远是所有链接都共享。 20 maxshared=3, 21 # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错 22 blocking=True, 23 # 一个链接最多被重复使用的次数,None表示无限制 24 maxusage=None, 25 # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 26 setsession=[], 27 # ping MySQL服务端,检查是否服务可用。 28 # 如:0 = None = never, 1 = default = whenever it is requested, 29 # 2 = when a cursor is created, 4 = when a query is executed, 7 = always 30 ping=0, 31 32 # 数据库信息 33 host=host, 34 port=int(port), 35 user=db_username, 36 password=db_password, 37 database=db_name, 38 charset=‘utf8‘ 39 ) 40 41 def create_conn_cursor(self): 42 # 创建连接 43 conn = self.pool.connection() 44 # 创建游标 45 cursor = conn.cursor(pymysql.cursors.DictCursor) 46 # 返回conn, cursor 47 return conn, cursor 48 49 def fetch_one(self, sql, args): 50 conn, cursor = self.create_conn_cursor() 51 cursor.execute(sql, args) 52 result = cursor.fetchone() 53 cursor.close() 54 conn.close() 55 return result 56 57 def fetch_many(self, sql, args): 58 conn, cursor = self.create_conn_cursor() 59 cursor.execute(sql) 60 result = cursor.fetchmany(args) 61 cursor.close() 62 conn.close() 63 return result 64 65 def fetch_all(self, sql, args): 66 conn, cursor = self.create_conn_cursor() 67 cursor.execute(sql, args) 68 result = cursor.fetchall() 69 cursor.close() 70 conn.close() 71 return result 72 73 def insert_one(self, sql, args): 74 conn, cursor = self.create_conn_cursor() 75 res = cursor.execute(sql, args) 76 conn.commit() 77 print(res) 78 conn.close() 79 return res 80 81 def insert_many(self, sql, args): 82 conn, cursor = self.create_conn_cursor() 83 res = cursor.executemany(sql, args) 84 conn.commit() 85 print(res) 86 conn.close() 87 return res 88 89 def update(self, sql, args): 90 conn, cursor = self.create_conn_cursor() 91 res = cursor.execute(sql, args) 92 conn.commit() 93 print(res) 94 conn.close() 95 return res 96 97 def delete(self, sql, args): 98 conn, cursor = self.create_conn_cursor() 99 res = cursor.execute(sql, args) 100 conn.commit() 101 print(res) 102 conn.close() 103 return res
test测试
1 from SQLHandler import SQLHandler 2 3 if __name__ == ‘__main__‘: 4 # 连接mysql 5 sqlhelper = SQLHandler("192.168.1.6", 3306, "root", "root", "datatest") 6 ## 查询 7 # 指定列名查询 8 # ret = sqlhelper.fetch_all("select * from user where id=%s",(2)) 9 # ret = sqlhelper.fetch_all("select * from user where name=%s",(‘apollo‘)) 10 # 显示查询结果第一条 11 # ret = sqlhelper.fetch_one("select * from user",None) 12 # 显示查询结果前两条 13 # ret = sqlhelper.fetch_many("select * from user",(2)) 14 # 显示查询结果全部 15 # ret = sqlhelper.fetch_all("select * from user", None) 16 # for (index, item) in enumerate(ret, 1): 17 # print(index, item) 18 19 20 ## 插入 21 # 插入一条数据 22 # 方式1: 23 # ret = sqlhelper.insert_one("insert into user VALUES (%s,%s,%s)",(10,"litch",56)) 24 # 方式2: 25 # ret = sqlhelper.insert_one("insert into user (name,age)VALUES (%s,%s)",("banana",12)) 26 # 插入多条数据 27 data = [] 28 for index in range(0,100000): 29 by = str(index) 30 name = "name2"+by 31 temp = (name,0,16) 32 data.append(temp) 33 sql = ‘insert into user(name,six,age) values(%s,%s,%s);‘ 34 ret = sqlhelper.insert_many(sql,data) 35 36 37 ## 更新 38 # ret = sqlhelper.update("update user SET name=%s WHERE id=%s",("Smith",1)) 39 40 41 ## 删除 42 # ret = sqlhelper.delete("delete from user where name=%s;",[("jack88")]) 43 print(ret)
以上是关于python操作数据库的主要内容,如果未能解决你的问题,请参考以下文章
[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段