封装mysql数据库,写sql语句的

import pymysql
import threading

lock = threading.Lock()


class Db:
def __init__(self):
self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='caobaofu5.9', charset='utf8',
db='p10', cursorclass=pymysql.cursors.DictCursor)
self.cursor = self.conn.cursor()

# 添加
def update(self, sql):
self.cursor.execute(sql)
self.conn.commit()
#添加之后可用直接返回他的id
return self.cursor.lastrowid

# 查询单个
def findone(self, sql):
lock.acquire()
self.cursor.execute(sql)
lock.release()
res = self.cursor.fetchone()
return res

# 查询所有
def findall(self, sql):
lock.acquire()
self.cursor.execute(sql)
lock.release()
res = self.cursor.fetchall()
return res

def colse(self):
self.cursor.close()
self.conn.close()


db1 = Db()

上一篇:(每日一练python)Redis 连接器


下一篇:python高级学习笔记Day03-- Ubuntu安装Mysql,navicat,python连接数据库,函数参数,闭包,SQL注入