import pymysql
# 定义一个数据库相关的配置项
DB_CONFIG = {'host': '127.0.0.1',
'user': 'root',
'password': '123',
'port': 3306,
'db': 'django',
'charset': 'utf8'
}
class SQLManager(object):
# 连接数据库
# 将conn,cursor作为类的属性,通过connect方法触发生成
def __init__(self):
self.conn = None
self.cursor = None
self.connect()
def connect(self):
self.conn = pymysql.connect(
host=DB_CONFIG['host'],
port=DB_CONFIG['port'],
user=DB_CONFIG['user'],
password=DB_CONFIG['password'],
db=DB_CONFIG['db'],
charset=DB_CONFIG['charset']
)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
# 查询多条数据
def get_all(self, sql, *args):
self.cursor.execute(sql, *args)
return self.cursor.fetchall()
# 查询一条数据
def get_one(self, sql, *args):
print(sql)
print(args)
self.cursor.execute(sql, *args)
return self.cursor.fetchone()
# 修改数据
def modify(self, sql, *args):
print(args)
self.cursor.execute(sql, args)
self.conn.commit()
# 关闭数据库cursor和连接
def close(self):
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
# conn = pymysql.connect(host='127.0.0.1', user='root', password='123', db='django', charset='utf8')
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#
# sql = "select * from classes where id=%s"
#
# cursor.execute(sql,1)
# classes = cursor.fetchone()
# print(classes)
db = SQLManager()
# print(db.get_all("select id,name from classes"))
# print(db.get_one("select * from %s" % ("classes") + " where id=%s", 1))
# db.modify("insert into classes (name) values (%s)",'脱产16期')
# db.modify("delete from classes where id=%s",10)
db.modify("update classes set name=%s where id=%s", '脱产160期', 19)
将pymysql封装成一个类
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...