import pymysql
conn = pymysql.connect(host=host,
user=user,
password=password,
db=db,
port=port,
charset="utf8",
cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor()
sql = "SELECT * from member WHERE LeaveAmount > %s LIMIT 0,3;"
cursor.execute(sql, args=(400,))
conn.commit()
result1 = cursor.fetchone()
result2 = cursor.fetchall()
print(result1)
print("=========")
print(result2)
cursor.close()
conn.close()
import pymysql
from py2020.fz.handle_config import do_config
class HandleMySql:
"""
处理数据库
"""
def __init__(self):
self.conn = pymysql.connect(host=do_config("mysql", "host"),
user=do_config("mysql", "user"),
password=do_config("mysql", "password"),
db=do_config("mysql", "db"),
port=do_config("mysql", "port"),
charset=do_config("mysql", "charset"),
cursorclass=pymysql.cursors.DictCursor)
self.cursor = self.conn.cursor()
def __call__(self, sql, arg=None, is_more=False):
"""
:param sql: sql语句,字符类型
:param arg: sql语句的参数,为序列类型
:param is_more: False or True
:return: 字典类型或者嵌套字典的列表
"""
self.cursor.execute(sql, arg)
self.conn.commit()
if is_more:
result = self.cursor.fetchall()
else:
result = self.cursor.fetchone()
return result
def close(self):
"""
关闭连接
:return:
"""
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
sql_1 = "SELECT * from member LIMIT 10;"
sql_2 = "SELECT * from member WHERE LeaveAmount > %s LIMIT 0,3;"
do_mysql = HandleMySql()
print(do_mysql(sql=sql_1, is_more=True))
print(do_mysql(sql=sql_2, arg=(600,), is_more=True))