gpt4 book ai didi

python - 循环输入数据库 Python 时出现异常

转载 作者:行者123 更新时间:2023-12-01 02:40:03 24 4
gpt4 key购买 nike

所以,我想以自增为主键多次输入数据,并返回主键作为输入结果。这是我的代码:

connectDB.py

import pymysql
class auth:

db = pymysql.connect("localhost","root","","rfid")

cursor = db.cursor()

def inputData(nama):
sql = "INSERT INTO auth (nama) VALUES ('%s');" % (nama)

try:
auth.cursor.execute(sql)
auth.db.commit()


result = auth.cursor.lastrowid

auth.db.close()

return result
except:
err = "Error: unable to fetch data"
auth.db.rollback()

auth.db.close()

return err

测试.py

import re
import PyMySQL
from connectDB import auth

while True:

inputs2 = input("masukan nama: ")


hasil = auth.inputData(inputs2)

print(hasil)

所以,当我第一次输入时是成功的,但是当我尝试再次输入时出现错误异常:

Traceback (most recent call last):
File "/home/pi/Desktop/learn/RFIDdatabase/connectDB.py", line 29, in inputData
auth.cursor.execute(sql)

File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 166, in execute
result = self._query(query)

File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 322, in _query
conn.query(q)

File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 855, in query
self._execute_command(COMMAND.COM_QUERY, sql)

File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 1071, in _execute_command
raise err.InterfaceError("(0, '')")
pymysql.err.InterfaceError: (0, '')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "test.py", line 12, in <module>
hasil = auth.inputData(inputs2)

File "/home/pi/Desktop/learn/RFIDdatabase/connectDB.py", line 41, in inputData
auth.db.rollback()

File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 792, in rollback
self._execute_command(COMMAND.COM_QUERY, "ROLLBACK")

File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 1071, in _execute_command
raise err.InterfaceError("(0, '')")
pymysql.err.InterfaceError: (0, '')

那么,异常原因是什么?

最佳答案

当然你会得到一个异常 - 因为你在执行查询后关闭连接:

auth.cursor.execute(sql)
auth.db.commit()

result = auth.cursor.lastrowid

auth.db.close() # < HERE

return result

您可能会遇到“对关闭的游标进行操作”的异常,该异常由过于宽泛的裸 except 子句 ( which is bad ) 处理 - 然后 - 回滚在 auth 处启动.db.rollback() 失败并出现非描述性且不可理解的错误。

其他问题:

关于python - 循环输入数据库 Python 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com