Python任意字典寫入MySQL
阿新 • • 發佈:2019-02-06
序言
INSERT
import pymysql
class Mysql:
def __init__(self, db_name, tb_name):
self.db = pymysql.connect('localhost', 'root', 'yellow', charset='utf8', db=db_name)
self.cursor = self.db.cursor()
self.tb = tb_name
def __del__(self):
self.cursor.close()
self. db.close()
def insert(self, dt):
ls = [(k, dt[k]) for k in dt if dt[k] is not None]
sql = 'insert %s (' % self.tb + ','.join([i[0] for i in ls]) +\
') values (' + ','.join(['%r' % i[1] for i in ls]) + ');'
self.cursor.execute(sql)
self.db.commit()
UPDATE
import pymysql
class Mysql:
def __init__(self, db_name):
self.db = pymysql.connect('localhost', 'root', 'yellow', charset='utf8', db=db_name)
self.cursor = self.db.cursor()
def __del__(self):
self.cursor.close()
self.db.close()
def commit(self, sql):
try :
self.cursor.execute(sql)
self.db.commit()
except Exception as error:
print('\033[031m', error, '\033[0m', sep='')
def update(self, dt_update, dt_condition, table):
sql = 'UPDATE %s SET ' % table + ','.join(['%s=%r' % (k, dt_update[k]) for k in dt_update])\
+ ' WHERE ' + ' AND '.join(['%s=%r' % (k, dt_condition[k]) for k in dt_condition]) + ';'
self.commit(sql)