附上代码
# -- encoding:utf-8 --
import pymysql
import pymssql
def SQLServer():
pymssql.connect()
def MySQL():
try:
host_input = input('请输入主机名')
user_input = input('请输入用户名')
pswd_input = input('请输入密码')
dbs_input = input('选择连接的数据库')
conn = pymysql.connect(host=host_input, user=user_input, password=pswd_input, database=dbs_input)
cur = conn.cursor()
while True:
sql = input('连接成功,输入需要执行的操作')
return_sql = cur.execute(sql)
print('影响的行数', return_sql)
except Exception as e:
print(e)
cur.close()
conn.close()
if __name__ == '__main__':
choice = input('请选择连接的数据库类型:1.SQLserver 2.MySQL')
if choice == '2':
MySQL()
elif choice == '1':
SQLServer()
else:
print('请输入正确的方法')
问题描述:
我使用了Python来连接MySQL,请问这个游标对象和连接对象的close()写的位置是正确的吗?因为之前没有加这个close()的时候代码运行也没有报错,如果说是错误的话还请指正一下
问题截图:
这是一个警告,因为cur和conn在try里定义的,可能还没运行时就因有错跳到except里了,而except之后的代码还会执行,这是的cur和conn就有可能没有定义。
所以有两种办法:一种在except里加一个return来跳出函数,另一种把cur.close()和conn.close()放到else中,这样只在没有出现异常的时候close。
第二种办法代码:
...
def MySQL():
try:
host_input = input('请输入主机名')
user_input = input('请输入用户名')
pswd_input = input('请输入密码')
dbs_input = input('选择连接的数据库')
conn = pymysql.connect(host=host_input, user=user_input, password=pswd_input, database=dbs_input)
cur = conn.cursor()
while True:
sql = input('连接成功,输入需要执行的操作')
return_sql = cur.execute(sql)
print('影响的行数', return_sql)
except Exception as e:
print(e)
else:
cur.close()
conn.close()
...