Python 3.x MySQL 功能封裝
阿新 • • 發佈:2019-01-10
摘要
最近要用Python寫一個Linux中繼,需要用到MySQL,然後就封裝了一下。
感興趣的小夥伴可以試試連線池,業務量大的時候還是很有用的:
手冊
配置與安裝
# 安裝好了之後,在db.py檔案中config字典中配置自己的資料庫
__config = {
'host':"123.32.32.18",
'port':3306,
'username':"root",
'password':"qq32",
'database':"WechatCard",
'charset' :"utf8"
}
使用
使用SQL語句直接操作
from db import MySQL
database = MySQL()
id = input('>>')
sql = "SELECT stu_uid FROM student WHERE id="+id
result = database.query(sql)
使用query_dic進行操作
result = database.query_dic({
'select': 'stu_uid',
'from': 'student',
'where': {
'id':id,
'iii':3
}
})
where也可以直接這麼寫,以實現複雜的條件判斷
result = database.query_dic({
'select': 'stu_uid',
'from': 'student',
'where': "id>2 and id<5"
})
刪除操作
result = database.query_dic({
'delete': 'student',
'where': "iii>5"
})
插入操作
database.query_dic({
'insert': 'student' ,
'domain_array':[
'stu_uid', 'iii'
],
'value_array':[
'asdf',33232
]
})
原始碼
(1) db.py
import pymysql
import types
class MySQL:
__db = None
# 在這裡配置自己的SQL伺服器
__config = {
'host':"123.32.32.18",
'port':3306,
'username':"root",
'password':"qq32",
'database':"WechatCard",
'charset' :"utf8"
}
def __init__(self):
self.__connect()
def __del__(self):
if(self.__db is not None):
self.__db.close()
def __connect(self):
if (self.__db == None):
self.__db = pymysql.connect(
host =self.__config['host'],
port =self.__config['port'],
user =self.__config['username'],
passwd =self.__config['password'],
db =self.__config['database'],
charset=self.__config['charset']
)
return self.__db
def query(self,_sql):
cursor = self.__connect().cursor()
try:
cursor.execute(_sql)
data = cursor.fetchall()
# 提交到資料庫執行
self.__connect().commit()
except:
# 如果發生錯誤則回滾
self.__connect().rollback()
return False
return data
def query_dic(self,_sql_dic):
if('select' in _sql_dic.keys()):
sql = "SELECT "+_sql_dic['select']+" FROM "+_sql_dic['from']+self.where(_sql_dic['where'])
print(sql)
return self.query(sql)
elif('insert' in _sql_dic.keys()):
sql = "INSERT INTO "+_sql_dic['insert']+self.quote(_sql_dic['domain_array'],type_filter=False)+" VALUES "+self.quote(_sql_dic['value_array'])
print(sql)
return self.query(sql)
if ('delete' in _sql_dic.keys()):
sql = "DELETE FROM " + _sql_dic['delete'] + self.where(_sql_dic['where'])
print(sql)
return self.query(sql)
def where(self, _sql):
if(isinstance(_sql,dict)==False):
return " WHERE "+ str(_sql)
if(isinstance(_sql,dict)):
_sql_dic = _sql
s = " WHERE "
index = 0
for domain in _sql_dic:
if(index==0):
s += domain+"="+ str(_sql_dic[domain]) +" "
index+=1
else:
s += "AND "+domain + "=" + str(_sql_dic[domain]) + " "
return s
# 為陣列加上外括號,並拼接字串
def quote(self, _data_array, type_filter=True):
s = "("
index = 0
if(type_filter):
for domain in _data_array:
if(index==0):
if (isinstance(domain, int)):
s += str(domain)
elif (isinstance(domain, str)):
s += "'" + domain + "'"
index+=1
else:
if(isinstance(domain, int)):
s += ", " + str(domain)
elif(isinstance(domain, str)):
s += ", " + "'" + domain + "'"
else:
for domain in _data_array:
if(index==0):
s += str(domain)
index+=1
else:
s += ", " + domain
return s+")"