got exception when do a loop input to database Python -




so, want input data in multiple times auto increment primary key , return primary key input result. there's code:

connectdb.py

import pymysql class auth:     db = pymysql.connect("localhost","root","","rfid")     cursor = db.cursor()     def inputdata(nama):        sql = "insert 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 fetch data"            auth.db.rollback()             auth.db.close()             return err 

test.py

import re import pymysql connectdb import auth  while true:       inputs2 = input("masukan nama: ")        hasil = auth.inputdata(inputs2)       print(hasil) 

so, when input in first time success when itry input again got error exception:

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

so, exception cause?

of course exception - cause close connection after executing query:

auth.cursor.execute(sql) auth.db.commit()  result = auth.cursor.lastrowid  auth.db.close()  # < here  return result 

you getting "operation on closed cursor" exception handled overly broad bare except clause (which bad) - - roll initiated @ auth.db.rollback() fails not descriptive , understandable error.

other issues:





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -

python - Read npy file directly from S3 StreamingBody -