一段封装的mysql代码,可以借鉴下
import pymysql
class MySqlModel(object):
def __init__(self, host, user, password, dbName):
self.host = host
self.user = user
self.password = password
self.dbName = dbName
def connet(self):
self.db = pymysql.connect(self.host, self.user, self.password, self.dbName)
self.cursor = self.db.cursor()
def close(self):
self.cursor.close()
self.db.close()
def get_on(self, sql):
"""
instance_sql:说明
从数据的table_name表,选择numeric字段最小的一条数据
"""
instance_sql = f"SELECT MIN(numeric) FROM table_name ;"
res = None
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchone()
self.close()
except:
print("查询失败")
return res
def get_all(self, sql):
res = ()
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchall()
self.close()
except:
print("查询失败")
return res
def insert(self, sql):
"""
instance_sql:说明
插入一条value数据到table_name表中
"""
value = (0, "ein", "tom", 10, 0)
table_name = "ILOVEFISHC"
instance_sql = f"insert into {table_name} values {value};"
return self._deit(sql)
def update(self, sql):
"""
update 表名 set 字段=新值,… where 条件
instance_sql说明:
更新table_name表的numeric字段,条件是numeric等于result
"""
numeric = ""
result = "6"
instance_sql = f"update table_name set numeric ={numeric} where numeric ={result};"
return self._deit(sql)
def delete(self, sql):
return self._deit(sql)
def create(self, sql):
return self._deit(sql)
def _deit(self, sql):
count = 0
try:
self.connet()
count = self.cursor.execute(sql)
self.db.commit()
self.close()
except:
print("事务提交失败")
self.db.rollback()
return count
|