一、寫函數的原因
寫這個函數的原因就是為了能夠不每次在用Python用數據庫的時候還要在寫一遍 做個通用函數做保留,也給大家做個小小的分享,函數不是最好的,希望有更好的代碼的朋友能提出 互相學習
二、函數代碼
PS:代碼是用Python3.6 寫的
import pymysql
class mysql (object):
def __init__(self, dbconfig):
"""
初始化連接信息
:param dbconfig: 連接信息的字典
"""
self.host = dbconfig['host']
self.port = dbconfig['port']
self.user = dbconfig['user']
self.passwd = dbconfig['passwd']
self.db = dbconfig['db']
self.charset = dbconfig['charset']
self._conn = None
self._connect()
self._cursor = self._conn.cursor ()
def _connect(self):
"""
連接數據庫方法
:return:
"""
try:
self._conn = pymysql.connect (host=self.host, port=self.port, user=self.user, passwd=self.passwd,
db=self.db, charset=self.charset)
except pymysql.Error as e:
print(e)
def query(self, sql):
try:
result = self._cursor.execute (sql)
except pymysql.Error as e:
print(e)
result = False
return result
def select(self, table, column='*', condition=''):
"""
查詢數據庫方法
:param table: 庫里面的表
:param column: 列字段
:param condition: 條件語句 (where id=1)
:return:
"""
condition = ' where ' + condition if condition else None
if condition:
sql = "select %s from %s %s" % (column, table, condition)
# print(sql)
else:
sql = "select %s from %s" %(column, table)
# print(sql)
self.query (sql)
return self._cursor.fetchall()
def insert(self,table,tdict):
"""
插入數據庫方法,replace去重插入 insert不去重插入
:param table: 表名
:param tdict: 要插入的字典
:return:
"""
column = ''
value = ''
for key in tdict:
column += ',' + key
value += "','" + tdict[key]
column = column[1:]
value = value[2:] + "'"
sql = "replace into %s(%s) values(%s)" %(table,column,value) # 去重
# sql = "insert into %s(%s) values(%s)" %(table,column,value) # 不去重
self._cursor.execute(sql)
self._conn.commit()
return self._cursor.lastrowid
def update(self,table,tdict,condition=''):
"""
更新數據庫方法
:param table: 表名
:param tdict: 更新數據庫數據字典
:param condition: 條件語句 (where id=1)
:return:
"""
if not condition:
print('must have id')
exit()
else:
condition = 'where ' + condition
value = ''
for key in tdict:
value += ",%s='%s'" %(key,tdict[key])
value = value[1:]
sql = "update %s set %s %s" %(table,value,condition)
# print(sql)
self._cursor.execute(sql)
self._conn.commit()
return self.affected_num()
def delete(self,table,condition=''):
"""
刪除方法
:param table: 表名
:param condition: 條件語句 (where id=1)
:return:
"""
condition = ' where ' + condition if condition else None
sql = "delete from %s %s" %(table,condition)
# print(sql)
self._cursor.execute(sql)
self._conn.commit()
return self.affected_num()
def all(self,*args):
"""
可以執行所有的SQL語句 相當於登錄到數據庫執行,就是返回結果沒有做處理 后期會更新
:param args: SQL 語句(select * from ssh)
:return:
"""
sql = input("請輸入SQL語句>>:")
sql = "%s" %sql
self._cursor.execute (sql)
self._conn.commit ()
return self._cursor.fetchall ()
def rollback(self):
"""
數據庫的事務
:return:
"""
self._conn.rollback()
def affected_num(self):
"""
受影響的條數
:return:
"""
return self._cursor.rowcount
def int_to_ip_or_ip_to_int(self,method,num,ip=''):
"""
主要是對數據庫的IP和數值之間的轉換
:param method: 轉換方法兩種(inet_ntoa,inet_aton)
:param num: 數值
:param ip: IP地址
:return:
"""
if method == 'inet_ntoa':
sql = "select %s(%s)" %(method,num)
elif method == 'inet_aton':
sql = "select %s(%s)" %(method,ip)
self.query(sql)
return self._cursor.fetchall()
def __del__(self):
"""
關閉連接
:return:
"""
try:
self._cursor.close ()
self._conn.close ()
except:
pass
def close(self):
"""
關閉連接
:return:
"""
self.__del__ ()
# 函數的使用
if __name__ == '__main__':
dbconfig = {
'host': '192.168.163.129', # MySQL地址
'port': 3306, # 端口
'user': 'root', # 用戶名
'passwd': '123456', # 密碼
'db': 'com_hosts', # 數據庫
'charset': 'utf8', # 字符集
}
db = mysql (dbconfig) # 初始化函數
# 查詢
print(db.select ('ssh'))
# 更新
print(db.update('ssh', tdict, 'Id=2'))
# 插入
print(db.insert('ssh',tdict))
# 刪除
print(db.delete('ssh','Id=6'))
# 執行SQL語句
while True:
a = db.all()
for i in a:
print(i)
db.close()
三、未實現功能(后續更新)
其實代碼的結果最好都是元祖,沒有對結果進行數據格式化顯示,后期會更新,大家用的時候根據需求對數據進行一些處理就好了,其實在公司是想寫個MySQL的管理平台的,以后寫好了會更新,也希望大家一起學習,可以QQ我
