Problems executing a MySQL query in python - python

I have problems when executing a method that allows me to eliminate a box in my program, this method is in charge of first eliminating everything that is inside the box and then it eliminates the box, this to avoid conflicts when dealing with foreign keys.
Here is my configuration for the connection:
import mysql.connector
connMySQL = mysql.connector.connect(
host='localhost',
db=wmszf,
user=root,
passwd='',
)
Here is the method:
def deleteBoxComplete(idBox):
cursor = connMySQL.cursor()
cursor.execute('FLUSH QUERY CACHE;')
cursor.close()
cursor = connMySQL.cursor()
cursor.execute(queryDelAllRefInBox(idBox))
connMySQL.commit()
cursor.close()
cursor = connMySQL.cursor()
cursor.execute(queryDeleteBox(idBox))
connMySQL.commit()
cursor.close()
You may notice that I clear the cache, as it is my priority to get the most up-to-date information possible.
Then I leave the query "queryDelAllRefInBox(idBox)":
DELETE FROM
picking_boxitem
WHERE
idBox_id = """+idBox+""";
Then I leave the query "queryDeleteBox(idBox)":
DELETE FROM
picking_box
WHERE
idBox = """+idBox+""";
The problem when executing the "deleteBoxComplete(idBox)" method is that it suddenly closes the connection with the database, it does so arbitrarily, sometimes yes, sometimes not, why does this happen? How can I prevent it? Is there a good practice that allows me to better execute this type of instructions?
Here is the output corresponding to the error:
Traceback (most recent call last):
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\USUARIO\Desktop\Projects\Produccion\wms\wms\picking\views.py", line 160, in listBoxesInPicking
boxes = getAllBoxInPicking(id)
File "C:\Users\USUARIO\Desktop\Projects\Produccion\wms\wms\MySQL\views.py", line 385, in getAllBoxInPicking
cursor = connMySQL.cursor()
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 809, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
Like other times this can come out:
Traceback (most recent call last):
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\USUARIO\Desktop\Projects\Produccion\wms\wms\picking\views.py", line 160, in listBoxesInPicking
boxes = getAllBoxInPicking(id)
File "C:\Users\USUARIO\Desktop\Projects\Produccion\wms\wms\MySQL\views.py", line 383, in getAllBoxInPicking
cursor.execute(queryGetAllBoxInPicking(idPicking))
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 384, in _handle_result
elif packet[4] == 0:
IndexError: bytearray index out of range
I appreciate your collaboration.
Additional things I've tried after no response
After looking for information, I found that the mysql engine probably works with much less performance than I imagined when cleaning the cache, so I chose to make a different configuration, instead of making a simple connection I decided to make a "pool connection" for the connections to be managed, the new configuration is as follows:
from django.conf import settings
from mysql.connector import Error
from mysql.connector import pooling
poolname="mysqlpool"
varHost='localhost'
varUser=settings.DATABASES['default']['USER']
varPasswd=settings.DATABASES['default']['PASSWORD']
varDB=settings.DATABASES['default']['NAME']
try:
connection_pool = pooling.MySQLConnectionPool(
pool_name="pynative_pool",
pool_size=10,
pool_reset_session=True,
host=varHost,
database=varDB,
user=varUser,
password=varPasswd)
print("Printing connection pool properties ")
print("Connection Pool Name - ", connection_pool.pool_name)
print("Connection Pool Size - ", connection_pool.pool_size)
connection_object = connection_pool.get_connection()
if connection_object.is_connected():
db_Info = connection_object.get_server_info()
print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info)
cursor = connection_object.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("Your connected to - ", record)
except Error as e:
print("Error while connecting to MySQL using Connection pool ", e)
finally:
if connection_object.is_connected():
db_Info = connection_object.get_server_info()
print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info)
cursor = connection_object.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("Your connected to - ", record)
However, I got the error that I got before, then I leave the traceability of the error:
Internal Server Error: /picking/listReferencesInBox/179/
Traceback (most recent call last):
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\USUARIO\Desktop\Projects\Produccion\wms\wms\picking\views.py", line 250, in listReferencesInBox
references = getReferencesInBoxMonitor(id)
File "C:\Users\USUARIO\Desktop\Projects\Produccion\wms\wms\MySQL\views.py", line 279, in getReferencesInBoxMonitor
cursor.execute(queryGetReferencesInBoxMonitor(idBox))
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 384, in _handle_result
elif packet[4] == 0:
IndexError: bytearray index out of range
The error occurs to me with the same frequency as before.

Related

Python and MySQL connector - Connection timed out error

I have a Python script which connects to my database, gets all the users' hashes and their emails, then parses through those hashes and gets some other data from the DB based on the user's hash value.
The problem is, that my MySQL Python connector breaks at various points and gives me this exception:
Traceback (most recent call last):
File "/home/antonio/.local/lib/python3.9/site-packages/mysql/connector/network.py", line 509, in open_connection
self.sock.connect(sockaddr)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/antonio/.local/lib/python3.9/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/antonio/.local/lib/python3.9/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/antonio/.local/lib/python3.9/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/antonio/.local/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/antonio/.local/lib/python3.9/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/antonio/.local/lib/python3.9/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/antonio/Desktop/PythonProjects/crypton-portfolio-api/crypto_tracking_coins/main_with_flask.py", line 701, in get_all_users_with_portfolio_and_accounting_data
user_coins_from_db = perform_db_query_fetchall('SELECT `portfolio`, `date`, `type`, `invested` FROM `users` WHERE `hash` = %s AND `fake` = "no"', (user_hash, ))
File "/home/antonio/Desktop/PythonProjects/crypton-portfolio-api/crypto_tracking_coins/helpers.py", line 6, in perform_db_query_fetchall
mydb = mysql.connector.connect(
File "/home/antonio/.local/lib/python3.9/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/home/antonio/.local/lib/python3.9/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/home/antonio/.local/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 716, in connect
self._open_connection()
File "/home/antonio/.local/lib/python3.9/site-packages/mysql/connector/connection.py", line 206, in _open_connection
self._socket.open_connection()
File "/home/antonio/.local/lib/python3.9/site-packages/mysql/connector/network.py", line 511, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (timed out)
My helpers.py file, which includes all the logic for performing SQL queries, looks like this:
import mysql.connector
from config import *
def perform_db_query_fetchall(query: str, params: tuple):
# Initiate DB connection
mydb = mysql.connector.connect(
host=DatabaseConfig.host_db,
user=DatabaseConfig.user_db,
password=DatabaseConfig.password_db,
database=DatabaseConfig.database_db
)
# Initiate DB cursor
c = mydb.cursor()
# Execute SQL query and get the results
c.execute(query, params)
results = c.fetchall()
# Close the DB connection
c.close()
mydb.close()
# Return the results
return results
def perform_db_query_fetchone(query: str, params: tuple):
# Initiate DB connection
mydb = mysql.connector.connect(
host=DatabaseConfig.host_db,
user=DatabaseConfig.user_db,
password=DatabaseConfig.password_db,
database=DatabaseConfig.database_db
)
# Initiate DB cursor
c = mydb.cursor()
# Execute SQL query and get the results
c.execute(query, params)
results = c.fetchone()
# Close the DB connection
c.close()
mydb.close()
# Return the results
return results
def perform_db_query_with_commit(query: str, params: tuple):
# Initiate DB connection
mydb = mysql.connector.connect(
host=DatabaseConfig.host_db,
user=DatabaseConfig.user_db,
password=DatabaseConfig.password_db,
database=DatabaseConfig.database_db,
autocommit=True
)
# Initiate DB cursor
c = mydb.cursor()
# Execute SQL query and get the results
c.execute(query, params)
# Close the DB connection
c.close()
mydb.close()
return
I'm looping with a for loop (about 1900 iterations of the loop) and doing approximately as twice as many SQL queries in that for loop.
It always ends not finishing the job that I need the script to do with just printing out the above mentioned Connection Timed Out exception.
Interesting fact is, that it always crashes on different stage. The last I tried, it failed on the 1600th~ iteration. Sometimes it fails on the 30th~ iteration...
Any ideas what can I do to fix it?
Thank you.
This can happen if the database server is running out of free space. In my case the database server was full.

How to handle "Redis.exceptions.ConnectionError: Connection has data"

I receive following output:
Traceback (most recent call last):
File "/home/ec2-user/env/lib64/python3.7/site-packages/redis/connection.py", line 1192, in get_connection
raise ConnectionError('Connection has data')
redis.exceptions.ConnectionError: Connection has data
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/ec2-user/env/lib64/python3.7/site-packages/eventlet/hubs/hub.py", line 457, in fire_timers
timer()
File "/home/ec2-user/env/lib64/python3.7/site-packages/eventlet/hubs/timer.py", line 58, in __call__
cb(*args, **kw)
File "/home/ec2-user/env/lib64/python3.7/site-packages/eventlet/greenthread.py", line 214, in main
result = function(*args, **kwargs)
File "crawler.py", line 53, in fetch_listing
url = dequeue_url()
File "/home/ec2-user/WebCrawler/helpers.py", line 109, in dequeue_url
return redis.spop("listing_url_queue")
File "/home/ec2-user/env/lib64/python3.7/site-packages/redis/client.py", line 2255, in spop
return self.execute_command('SPOP', name, *args)
File "/home/ec2-user/env/lib64/python3.7/site-packages/redis/client.py", line 875, in execute_command
conn = self.connection or pool.get_connection(command_name, **options)
File "/home/ec2-user/env/lib64/python3.7/site-packages/redis/connection.py", line 1197, in get_connection
raise ConnectionError('Connection not ready')
redis.exceptions.ConnectionError: Connection not ready
I couldn't find any issue related to this particular error. I emptied/flushed all redis databases, so there should be no data there. I assume it has something to do with eventlet and patching. But even when I put following code right at the beginning of the file, the error appears.
import eventlet
eventlet.monkey_path()
What does this error mean?
Finally, I came up with the answer to my problem.
When connecting to redis with python, I specified the database with the number 0.
redis = redis.Redis(host=example.com, port=6379, db=0)
After changing the dabase to number 1 it worked.
redis = redis.Redis(host=example.com, port=6379, db=1)
Another way is to set protected_mode to no in etc\redis\redis.conf. Recommended when running redis locally.

Error on writing to Google cloud spanner using Google cloud functions

I am trying to insert data into cloud spanner table using cloud functions but it is throwing the error given below.Reading data from cloud spanner is working properly but writing using both the Data Definition Language commands and batch.insert method both throws the same error. I am thinking its some kind of permissions problem! I don't know how to fix it?
Requirements file contains only google-cloud-spanner==1.7.1
Code running in cloud functions
import json
from google.cloud import spanner
INSTANCE_ID = 'AARISTA'
DATABASE_ID = 'main'
TABLE_NAME = 'userinfo'
dataDict = None
def new_user(request):
dataDict = json.loads(request.data)# Data is available in dict format
if dataDict['USER_ID']==None:
return "User id empty"
elif dataDict['IMEI'] == None:
return "Imei number empty"
elif dataDict['DEVICE_ID'] == None:
return "Device ID empty"
elif dataDict['NAME'] == None:
return "Name field is empty"
elif dataDict['VIRTUAL_PRIVATE_KEY']== None:
return "User's private key cant be empty"
else:
return insert_data(INSTANCE_ID,DATABASE_ID)
def insert_data(instance_id, database_id):
spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
def insert_user(transcation):
row_ct= transcation.execute_update("INSERT userinfo
(USER_ID,DEVICE_ID,IMEI,NAME,VIRTUAL_PRIVATE_KEY) VALUES"
"("+dataDict['USER_ID']+',
'+dataDict['DEVICE_ID']+', '+ dataDict['IMEI']+',
'+dataDict['NAME']+',
'+dataDict['VIRTUAL_PRIVATE_KEY']+")")
database.run_in_transaction(insert_user)
return 'Inserted data.'
Error logs on Cloud Functions
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/spanner_v1/pool.py", line 265, in get session = self._sessions.get_nowait()
File "/opt/python3.7/lib/python3.7/queue.py", line 198, in get_nowait return self.get(block=False)
File "/opt/python3.7/lib/python3.7/queue.py", line 167, in get raise Empty _queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable return callable_(*args, **kwargs)
File "/env/local/lib/python3.7/site-packages/grpc/_channel.py", line 547, in __call__ return _end_unary_response_blocking(state, call, False, None)
File "/env/local/lib/python3.7/site-packages/grpc/_channel.py", line 466, in _end_unary_response_blocking raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with: status = StatusCode.INVALID_ARGUMENT details = "Invalid CreateSession request." debug_error_string = "{"created":"#1547373361.398535906","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1036,"grpc_message":"Invalid> CreateSession request.","grpc_status":3}" >
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 297, in run_http_function result = _function_handler.invoke_user_function(flask.request)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 199, in invoke_user_function return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 192, in call_user_function return self._user_function(request_or_event)
File "/user_code/main.py", line 21, in new_user return insert_data(INSTANCE_ID,DATABASE_ID)
File "/user_code/main.py", line 31, in insert_data database.run_in_transaction(insert_user)
File "/env/local/lib/python3.7/site-packages/google/cloud/spanner_v1/database.py", line 438, in run_in_transaction with SessionCheckout(self._pool) as session:
File "/env/local/lib/python3.7/site-packages/google/cloud/spanner_v1/pool.py", line 519, in __enter__ self._session = self._pool.get(**self._kwargs)
File "/env/local/lib/python3.7/site-packages/google/cloud/spanner_v1/pool.py", line 268, in get session.create()
File "/env/local/lib/python3.7/site-packages/google/cloud/spanner_v1/session.py", line 116, in create session_pb = api.create_session(self._database.name, metadata=metadata, **kw)
File "/env/local/lib/python3.7/site-packages/google/cloud/spanner_v1/gapic/spanner_client.py", line 276, in create_session request, retry=retry, timeout=timeout, metadata=metadata
File "/env/local/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__ return wrapped_func(*args, **kwargs)
File "/env/local/lib/python3.7/site-packages/google/api_core/retry.py", line 270, in retry_wrapped_func on_error=on_error,
File "/env/local/lib/python3.7/site-packages/google/api_core/retry.py", line 179, in retry_target return target()
File "/env/local/lib/python3.7/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout return func(*args, **kwargs)
File "/env/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Invalid CreateSession request.
I tried to reproduce this but it seems to work for me as a Python 3.7 function. I used the latest google-cloud-spanner library in requirements.txt.
While I am unsure what would be causing your error I did notice a few other things.
It seemed odd to declare a global dataDict and not use the one constructed and pass it. Instead I added that as a param to the insert method.
The spacing of the query was a bit odd and the use of single and double quotes was odd. this made it hard to parse visually. As the function runs as python 3.7 you can also use f-strings which likely would make it even more readable.
Here is the code I ran in a function that seemed to work.
import json
from google.cloud import spanner
INSTANCE_ID = 'testinstance'
DATABASE_ID = 'testdatabase'
TABLE_ID = 'userinfo'
def new_user(request):
data = { 'USER_ID': '10', 'DEVICE_ID': '11' }
return insert_data(INSTANCE_ID, DATABASE_ID, data)
def insert_data(instance_id, database_id, data):
spanner_client = spanner.Client()
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
def insert_user(transaction):
query = f"INSERT {TABLE_ID} (USER_ID,DEVICE_ID) VALUES ({data['USER_ID']},{data['DEVICE_ID']})"
row_ct = transaction.execute_update(query)
database.run_in_transaction(insert_user)
return 'Inserted data.'

Python code for ldapsearch

I have a script:
ldapsearch -xLL -h 10.4.113.46 -D 'E900000#corp.privatedev' -W -b 'dc=corp,dc=privatedev' '(cn=lc_proxy_pentest)'
It runs well.
I programme with python to make the same query:
from ldap3 import Server, Connection, ALL
....
server = Server('10.4.113.46', get_info=ALL)
conn = Connection(server, 'uid=E900000#corp.privatedev,cn=lc_proxy_pentest,dc=corp,dc=privatedev', 'PaSsWoRd', auto_bind=True)
The error shows:
Traceback (most recent call last): File "<input>", line 1, in <module>
File "C:\Users\E900000\Python\lib\site-packages\ldap3\core\connection.py", line 278, in __init__
self.bind(read_server_info=True)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\core\connection.py", line 427, in bind
response = self.post_send_single_response(self.send('bindRequest', request, controls))
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\sync.py", line 122, in post_send_single_response
responses, result = self.get_response(message_id)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\base.py", line 298, in get_response
responses = self._get_response(message_id)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\sync.py", line 168, in _get_response
dict_response = self.decode_response(ldap_resp)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\base.py", line 403, in decode_response
result = bind_response_to_dict(component)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\operation\bind.py", line 119, in bind_response_to_dict
'saslCreds': bytes(response['serverSaslCreds']) if response['serverSaslCreds'] is not None else None}
File "C:\Users\E900000\Python\lib\site-packages\pyasn1\type\univ.py", line 984, in __bytes__
return bytes(self._value) TypeError: cannot convert 'NoValue' object to bytes
If I programme just
server = Server('10.4.113.46')
conn = Connection(server)
conn.bind()
The third line brings the same error.
What's wrong?
I doubt that E900000#corp.privatedev corresponds to uid=E900000#corp.privatedev,cn=lc_proxy_pentest,dc=corp,dc=privatedev
I am assuming you are using Active Directory (based on E900000#corp.privatedev).
Try using dsquery to Determine the FDN for the user.
The reason of the failed connection can be refered https://github.com/etingof/pyasn1/issues/52.
But after I modify the library and enable a successful connection, the ldapsearch still doesn‘t work.

got exception when do a loop input to database Python

So, I want to input data in multiple times with auto increment as primary key and return the primary key as the input result. so there's my code:
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)
so, when I do an input in the first time is success but when Itry to input again I got an 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 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, '')
so, What the exception cause?
Of course you would get an exception - cause you close the connection after executing a query:
auth.cursor.execute(sql)
auth.db.commit()
result = auth.cursor.lastrowid
auth.db.close() # < HERE
return result
You probably getting an "operation on a closed cursor" exception which is handled by your overly broad bare except clause (which is bad) - then - the roll back is initiated at auth.db.rollback() which fails with a not descriptive and understandable error.
Other issues:
I would make the db and cursor instance variables instead of class variables (differences)
don't "string format" your queries - proper parameterize them

Categories

Resources