Python, MySQL and a weird error - python

I have a bug that I don't know how to fix or even reproduce:
query = "SELECT id, name FROM names ORDER BY id"
results = database.execute(query)
where the class Database contains:
def execute(self, query):
cursor = self.db.cursor()
try:
cursor.execute(query)
return cursor.fetchall()
except:
import traceback
traceback.print_exc(file=debugFile)
return []
This is how I open the database connection:
self.db = MySQLdb.connect(
host=mysqlHost,
user=mysqlUser,
passwd=mysqlPasswd,
db=mysqlDB
)
This is the stacktrace of the error:
File "foo.py", line 169, in application results = config.db.execute(query)
File "Database.py", line 52, in execute
return cursor.fetchall()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 340, in fetchall
self._check_executed()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 70, in _check_executed
self.errorhandler(self, ProgrammingError, "execute() first")
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: execute() first
Do you have any ideas of why this is happening and how can I fix it? I searched on the internet and I found out that the reason may be having 2 cursors, but I have only one.

try this in your traceback it's for debugging:
except ProgrammingError as ex:
if cursor:
print "\n".join(cursor.messages)
# You can show only the last error like this.
# print cursor.messages[-1]
else:
print "\n".join(self.db.messages)
# Same here you can also do.
# print self.db.messages[-1]

Related

raise errors.InterfaceError("No result set to fetch from.") mysql.connector.errors.InterfaceError: No result set to fetch from. Error

I have had this MySQL error for quite some time now. I cant seem to understand why it keeps occurring, I have imported my database file with all the right information to make the connection but for some reason the error still occurs. I have similar functionality scattered all over my project and I have never got this error, it is literally word for word copying and yet I still get this error. If someone could point me in the right direction it would be much appreciated as I have had no luck online.
Thanks.
Code:
def membership_reactivation(self):
connection.connect(user="root", password="")
email = self.EmailBox.get()
password = self.PasswordBox.get()
query = "UPDATE users SET Status = 'ACTIVE' WHERE Email = %s AND Password = %s;"
cursor.execute(query, (email, password,))
result = cursor.fetchall()
if result:
connection.commit()
connection.close()
self.controller.show_frame("ThankYou")
else:
print("Credentials Not Found in Database.")
connection.close()
Error Message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\AJE\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\AJE\PycharmProjects\ReactivateMembership.py", line 58, in membership_reactivation
result = cursor.fetchall()
File "C:\Users\AJE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\cursor.py", line 1002, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
mysql.connector.errors.InterfaceError: No result set to fetch from.

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

Hive - python connection error

Here is code :
#!/usr/bin/env python
import pyhs2
try:
with pyhs2.connect(host='localhost',
port=10001,
authMechanism="PLAIN",
user='root',
password='test',
database='test') as conn:
with conn.cursor() as cur:
#Show databases
print cur.getDatabases()
#Execute query
cur.execute("select * from raw_stats")
#Return column info from query
print cur.getSchema()
#Fetch table results
for i in cur.fetch():
print i
except Thrift.TException, tx:
print '%s' % (tx.message)
Error!
Traceback (most recent call last): File "/usr/local/py/test.py", line
8, in database='default') as conn: File
"/usr/lib/python2.6/site-packages/pyhs2/init.py", line 7, in
connect
return Connection(*args, **kwargs) File "/usr/lib/python2.6/site-packages/pyhs2/connections.py", line 46, in
init
transport.open() File "/usr/lib/python2.6/site-packages/pyhs2/cloudera/thrift_sasl.py", line
55, in open
self._trans.open() File "/usr/lib64/python2.6/site-packages/thrift/transport/TSocket.py", line
101, in open
message=message) thrift.transport.TTransport.TTransportException: Could not connect to localhost:10001
It resolved by starting hiveServer2 service and changing the port 10000.

python mysqldb how to correctly escape urls

I'm trying to correctly escape urls to enter into a mysql connection, but apparently I'm doing it wrong:
>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost",user="...",passwd="...",db="...")
>>> cur = db.cursor()
>>> cmd = "insert into S3_data (url) VALUES ('http://google.com')"
>>> cur.execute(cmd)
1
>>> cur.execute(MySQLdb.escape_string(cmd))
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
cur.execute(MySQLdb.escape_string(cmd))
File "C:\Python34\lib\site-packages\MySQLdb\cursors.py", line 220, in execute
self.errorhandler(self, exc, value)
File "C:\Python34\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorvalue
File "C:\Python34\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
r = self._query(query)
File "C:\Python34\lib\site-packages\MySQLdb\cursors.py", line 371, in _query
rowcount = self._do_query(q)
File "C:\Python34\lib\site-packages\MySQLdb\cursors.py", line 335, in _do_query
db.query(q)
File "C:\Python34\lib\site-packages\MySQLdb\connections.py", line 280, in query
_mysql.connection.query(self, query)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\'http://google.com\\')' at line 1")
As you can see the command works ok, but the escaping fails. What am I missing here?
Also, does escape string handle multi-byte encodings?
Thanks
I believe if you use parameters you shouldn't have a problem.
cmd = "INSERT INTO S3_data (url) VALUES (%s)"
args = 'http://google.com'
cur.execute(cmd, args)

SQLAlchemy + postgres : (InternalError) current transaction is aborted, commands ignored until end of transaction block

I am attempting to save a parent/children set of records, and I want to wrap the inserts in a transaction. I am using SQLAlchemy with postgresql 8.4.
Here is a snippet of my code:
def insert_data(parent, child_rows):
# Start a transaction
conn = _get_connection()
tran = conn.begin()
try:
sql = get_sql_from_parent(parent)
res = conn.execute(sql) # <- Code barfs at this line
item = res.fetchone() if res else None
parent_id = item['id'] if ((item) and ('id' in item)) else -1
if parent_id == -1:
raise Exception('Parent could not be saved in database')
# Import children
for child in child_rows:
child_sql = get_child_sql(parent_id, child)
conn.execute(child_sql)
tran.commit()
except IntegrityError:
pass # rollback?
except Exception as e:
tran.rollback()
print "Exception in user code:"
print '-'*60
traceback.print_exc(file=sys.stdout)
print '-'*60
When I invoke the function, I get the following stacktrace:
Traceback (most recent call last):
File "import_data.py", line 125, in <module>
res = conn.execute(sql)
File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1405, in execute
params)
File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1582, in _execute_text
statement, parameters
File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1646, in _execute_context
context)
File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1639, in _execute_context
context)
File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.7.4-py2.6-linux-x86_64.egg/sqlalchemy/engine/default.py", line 330, in do_execute
cursor.execute(statement, parameters)
InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block
...
Does anyone know why I am getting this cryptic error - and how do I resolve it?
Can you activate the log query on postgresql ? (min_duration set to 0 in postgresql.conf then restart).
Then look at your postgresql logs to debug it.

Categories

Resources