import pymysql
class skq:
「」" 「」"
def __init__(self):
config =
# 建立連線
self.connection = pymysql.connect(**config)
def add(self, _dict, table):
# 執行sql語句
try:
with self.connection.cursor() as cursor:
_listindex = list(_dict.keys())
_list = list(_dict.values())
values = ["'{}'".format(i) for i in _list]
item = "{}".format(','.join(_listindex))
value = "{}".format(','.join(values))
sql = "insert into {} ({}) values({});".format(table, item, value)
print(sql)
cursor.execute(sql)
self.connection.commit()
return true
except exception as e:
print(e)
self.connection.rollback()
def updata(self, table, values_dict, upvalues_dict):
# update table_name set field1=new-value1, field2=new-value2
# [where clause]
try:
with self.connection.cursor() as cursor:
value =
dict_list = values_dict.items()
for i in dict_list:
if i[1]:
value += ["{} = '{}'".format(i[0], i[1])]
upvalue =
updict_list = upvalues_dict.items()
for i in updict_list:
if i[1]:
upvalue += ["{} = '{}'".format(i[0], i[1])]
sql = "update {} set {} where {};".format(table, ' , '.join(upvalue), ' and '.join(value))
print(sql)
cursor.execute(sql)
self.connection.commit()
return true
except exception as e:
print(e)
self.connection.rollback()
def findall(self, table, item, values_dict):
# 執行sql語句
try:
with self.connection.cursor() as cursor:
value =
dict_list = values_dict.items()
for i in dict_list:
if i[1]:
value += ["{} = '{}'".format(i[0], i[1])]
sql = "select {} from {} where {};".format(item, table, ' and '.join(value))
# print(sql)
cursor.execute(sql)
# 獲取查詢結果
result = cursor.fetchall() # 獲取全部結果,取一條為 fetchone()
return result
except exception as e:
print(e)
self.connection.rollback()
def getmax(self, table, item):
try:
with self.connection.cursor() as cursor:
sql = 'select max({}) from {};'.format(item, table)
print(sql)
cursor.execute(sql)
# 獲取查詢結果
result = cursor.fetchall() # 獲取全部結果,取一條為 fetchone()
return result
except exception as e:
print(e)
self.connection.rollback()
def dell(self, table, values_dict):
# 執行sql語句
try:
with self.connection.cursor() as cursor:
value =
dict_list = values_dict.items()
for i in dict_list:
if i[1]:
value += ["{} like '{}'".format(i[0], i[1])]
sql = "delete from `{}` where {};".format(table, ' and '.join(value))
print(sql)
cursor.execute(sql)
# 獲取查詢結果
self.connection.commit()
return true
except exception as e:
print(e)
self.connection.rollback()
對pymysql的簡單封裝
coding utf 8 usr bin python import pymysql class mysql 對pymysql的簡單封裝 def init self,host,user,pwd,db self.host host self.user user self.pwd pwd self.db...
python 封裝pymysql的思路步驟
目標 封裝乙個模組 功能,呼叫模組,可以快捷的操作pymysql 的相關功能 分析 pymysql並不是一匯入就可以用的 使用之前要做一些事情 考慮 把使用前必做的事情,放到初始化的init方法中 更進一步 pymysql在使用之前,得先 1,連線mysql,獲得連線物件 2,通過連線物件,獲得游標...
基礎類封裝 pymysql庫操作mysql封裝
1 import pymysql 2from lib.logger import logger 3from warnings import filterwarnings 4 filterwarnings ignore category pymysql.warning 忽略mysql警告資訊56 cl...