在try-except块中关闭游标后,可以通过以下方法关闭连接:
示例代码:
import psycopg2
try:
connection = psycopg2.connect(database="mydb", user="myuser", password="mypassword", host="localhost", port="5432")
cursor = connection.cursor()
# 执行数据库操作
except Exception as e:
# 处理异常
finally:
if cursor is not None:
cursor.close()
if connection is not None:
connection.close()
示例代码:
import psycopg2
try:
with psycopg2.connect(database="mydb", user="myuser", password="mypassword", host="localhost", port="5432") as connection:
with connection.cursor() as cursor:
# 执行数据库操作
except Exception as e:
# 处理异常
以上是针对PostgreSQL数据库的示例代码,如果是其他数据库,如MySQL、Oracle等,可以根据相应的数据库驱动和连接方式进行调整。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云