学习封装了MySQL的类

#!/usr/bin/python3

import pymysql
import read_config

class MysqlDb:

#初始化
def __init__(self,host=read_config.host,port=read_config.port,user=read_config.user,password=read_config.password,database=read_config.database):
self.host = str(host)
self.port = int(port)
self.user = str(user)
self.password = str(password)
self.database = str(database)

#获取连接
def getDb(self):
try:
self.db=pymysql.connect(self.host,self.user,self.password,self.database,self.port,charset='utf8')
return self.db
except Exception as e:
raise e

#插入
def insert(self,table,data):
sql=''
for key in data:
data[key] ="'" +str(data[key]) +"'"
key =','.join(data.keys())
values =','.join(data.values())
sql = "insert into " +table+ "(" +key+ ")values(" +values+ ");"

self.cursor = self.getDb().cursor()

try:
self.cursor.execute(sql)
self.db.commit()
last_id = self.cursor.lastrowid
return last_id

except Exception as e:
print(e)
self.getDb().rollback()

finally:
self.cursor.close()

#获取单条记录
def fetchAll(self,sql):
self.cursor = self.getDb().cursor()

try:
self.cursor.execute(sql)
data = self.cursor.fetchall()
return data
except Exception as e:
print(e)
finally:
self.cursor.close()

#更新数据
def update(self,sql):
self.cursor = self.getDb().cursor()

try:
self.cursor.execute(sql)
self.getDb().commit()
return True
except Exception as e:
print(e)
self.getDb().rollback()
finally:
self.cursor.close()

#删除数据
def drop(self,sql):
self.cursor = self.getDb().cursor()

try:
self.cursor.execute(sql)
self.getDb().commit()
return True
except Exception as e:
print(e)
self.getDb().rollback()
finally:
self.cursor.close()




# db = MysqlDb()
# print(db.drop("DELETE from cc_user WHERE user_id = 6;"))
# print(db.update("update cc_user set password = \"654321\" WHERE user_id = 6"))
# print(db.fetchAll("select * from cc_user where user_id = 6"))
# print(db.insert('cc_user',{'username':"mengzhu", 'nickname':"岁月是把杀猪刀", 'password':"123456", 'create_time':"1586850036"}))

刚学习,感觉python类和方法看不了底层,怎样追踪底层方法和类,请大家多多指教


posted @ 2020-04-23 16:59  一个在黑夜敲代码的人  阅读(47)  评论(0)    收藏  举报