pymysql.cursors 普通连接:
import pymysql.cursors
conn = pymysql.connect(host="127.0.0.1",port=9030, user="root", password="", database="ssb", charset='utf8')
mycursor = conn.cursor()
mycursor.execute("select * from lineorder_rt limit 1")
result = mycursor.fetchall()
for data in result:
print(data)
# 使用完后,要把游标和 连接都要关闭掉
cursor.close()
conn.close()
问题:为了避免出现连接超时中断错误
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError)(2013,'Lost connection to MySQL server during query')
添加事务操作后的连接:
import pymysql.cursors
connect = pymysql.connect(host="127.0.0.1", port=8090, user=self.user_doris_prd, password=self.password_doris_prd, database="ads", charset='utf8')
while True:
try:
with connect.cursor() as cursor: # 获取游标
cursor.execute(sql)
connect.commit()
result = cursor.fetchone()
# 使用完后,要把游标和 连接都要关闭掉
cursor.close()
connect.close()
for data in result:
print(data)
break
except Exception:
connect.ping(True)
补充:cursor 提供了 fetchone()、fetchall() 和 fetchmany() 函数
参考:python中查询数据库用到的 fetchone()、fetchall()和fetchmany() 函数_cur.fetchall()-CSDN博客