话不多说,直接贴源代码
import pymysql
import time
class DbCheck():
"""数据库连接类"""
def __init__(self, sql, count):
self.conn = ''
self.result = []
self.sql = sql
self.count = count
self.connect()
def connect(self):
self.conn = pymysql.connect(host=ip or hostname,
port=3306,
user=username,
password=passw,
db=dbname,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
def execute_sql(self):
"""
执行 SQL 查询
:param sql:
:param count:
:return:
"""
if not self.conn:
self.connect()
for _ in range(3):
try:
with self.conn.cursor() as cursor:
cursor.execute(self.sql)
self.result = cursor.fetchall()
# if self.count == 1:
# result = cursor.fetchone()
# else:
# result = cursor.fetchall()
# if self.count > 1:
# result = result[:self.count]
self.conn.commit()
# print('\n{sql}\n--->>>\t{result}\n{sep}\n'.format(sep='=' * 80, sql=sql, result=result))
return self.result
except pymysql.err.MySQLError:
self.conn.close()
self.connect()
if __name__ == "__main__":
sql = "SELECT * FROM item where (unix_timestamp(NOW()) - FuiCreateTime < 6000);"
db = DbCheck(sql, 2)
db.execute_sql()
这里自己把对应connect的参数填上应该就能连接数据库进行操作了。
也可以在init里面传入参数进行连接。
实测可以执行。