在对数据库Python进行循环输入时出现异常

时间:2017-08-22 03:52:42

标签: python python-3.x pymysql

因此,我希望以自动增量为主键多次输入数据,并返回主键作为输入结果。所以我的代码是:

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

test.py

import re
import PyMySQL
from connectDB import auth

while True:

     inputs2 = input("masukan nama: ")


     hasil = auth.inputData(inputs2)

     print(hasil)

所以,当我第一次做输入成功但是当Itry再次输入时我得到一个错误异常:

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, '')

那么,异常是什么原因造成的?

1 个答案:

答案 0 :(得分:2)

当然你会得到一个例外 - 因为你在执行查询后关闭了连接

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

result = auth.cursor.lastrowid

auth.db.close()  # < HERE

return result

您可能会收到“关闭游标上的操作”异常,该异常由您过于宽泛的except子句which is bad处理 - 然后 - 在auth.db.rollback()处启动回滚失败时没有描述性和可理解的错误。

其他问题: