您的位置:首页 > 汽车 > 时评 > Python 连接 Doris pymysql游标cursor.excute(sql) 并且添加事务和自动重连操作

Python 连接 Doris pymysql游标cursor.excute(sql) 并且添加事务和自动重连操作

2024/7/6 0:16:02 来源:https://blog.csdn.net/m0_63628018/article/details/140052843  浏览:    关键词:Python 连接 Doris pymysql游标cursor.excute(sql) 并且添加事务和自动重连操作

 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.cursorsconnect = 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)breakexcept Exception:connect.ping(True)

补充:cursor 提供了 fetchone()、fetchall() 和 fetchmany() 函数

参考:python中查询数据库用到的 fetchone()、fetchall()和fetchmany() 函数_cur.fetchall()-CSDN博客

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com