import pymysql
import threading
MYSQL_HOST = '192.168.1.248'
MYSQL_USER = 'moxiao'
MYSQL_PASSWORD = 'xxxx'
MYSQL_PORT = 3306
DATABASE = 'xxxx'
lock = threading.Lock()
class MysqlConn:
def __init__(self, host=MYSQL_HOST, username=MYSQL_USER, password=MYSQL_PASSWORD, port=MYSQL_PORT,
database=DATABASE):
"""
mysql 初始化
:param host:
:param username:
:param password:
:param port:
"""
try:
self.db = pymysql.Connection(host=host, user=username, password=password,
database=database, port=port)
self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor) # TODO 最主要的一行。。。
except pymysql.MySQLError as e:
print(e.args)
def insert(self, table, data):
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
sql = 'insert into %s (%s) values (%s)' % (table, keys, values)
try:
self.cursor.execute(sql, tuple(data.values()))
self.db.commit()
except pymysql.MySQLError as e:
print(e.args)
self.db.rollback()
def insert_many(self, table, data):
if isinstance(data, list) or isinstance(data, tuple):
keys = str(tuple(data[0].keys())).replace('(', '').replace(')', '').replace("'", '')
sql = 'insert into %s (%s) value' % (table, keys) + ' (' + '%s, ' * (len(data[0].keys()) - 1) + '%s);'
values = [tuple(d.values()) for d in data]
if lock.acquire():
try:
self.cursor.executemany(sql, values)
self.db.commit()
except pymysql.MySQLError as e:
print(e.args)
self.db.rollback()
finally:
lock.release()
def find_key_val(self, table, key_val):
sql = None
if isinstance(key_val, str):
sql = 'SELECT * FROM `%s` WHERE %s ;' % (table, key_val)
elif isinstance(key_val, dict):
sql_where = ''
for item in key_val.items():
row_str = str(item[0]) + '=' + str(item[1]) + ' and '
sql_where += row_str
sql_where = sql_where[:-4]
sql = 'SELECT * FROM `%s` WHERE %s ;' % (table, sql_where)
if sql:
try:
self.cursor.execute(sql)
data = self.cursor.fetchall()
if len(data) > 0:
return data
return None
except pymysql.MySQLError as e:
print(e.args)
return None
def find_by_sql(self, sql):
if sql:
try:
self.cursor.execute(sql)
data = self.cursor.fetchall()
if len(data) > 0:
return data
return None
except pymysql.MySQLError as e:
print(e.args)
return None
def del_by_sql(self, sql):
if sql:
try:
self.cursor.execute(sql)
self.db.commit()
return True
except pymysql.MySQLError as e:
print(e.args)
self.db.rollback()
return None
def update_by_sql(self, sql):
if sql:
try:
self.cursor.execute(sql)
self.db.commit()
return True
except pymysql.MySQLError as e:
print(e.args)
self.db.rollback()
return None
def close(self):
try:
self.cursor.close()
except:
pass
try:
self.db.close()
except:
pass
if __name__ == '__main__':
mc = MysqlConn()
result = mc.find_by_sql('select * from tst;')
print(result)