Getting an error when using prepared statement in python - python

whenever I try to run a normal query all works perfectly fine. the code executes and I can get the results but whenever I try to use a prepared statement in python I keep getting the following error:
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? WHERE name = ?' at line 1
The code I'm trying to run:
cursor = con.db.cursor(prepared=True)
try:
cursor.execute("SELECT * FROM %s WHERE name = %s", ('operations', 'check', ))
except mysql.connector.Error as error:
print(error)
except TypeError as e:
print(e)
I've tried also to change the tuple object to string and removed one of the '%s' just for checking. but I still get an error for the '%s' synax.
another thing I've tried is to use a dict object so I've changed the '%s' to '%(table)s' and '%(name)s' and used a dict of
{'table': 'operations', 'name': 'check'}
example:
cursor.execute("SELECT * FROM %(table)s WHERE name = %(name)s", {'table': 'operations', 'name': 'check'})
but again it didn't worked and I still got the exception
am I missing something?
Thanks in advance!
-------- Edit --------
Thanks to #khelwood, I've fixed the problem.
as #khelwood mentioned in comments the problem was because I tried to use the '%s' as a parameter for table name.
python prepared statements can't handle parameters for things such as table names
so thats what throwed the exception

You can't insert a table name as a query parameter. You can pass the name you're looking for as a parameter, but it should be in a tuple: ("check",)
So
cursor.execute("SELECT * FROM operations WHERE name = %s", ("check", ))

Related

How do you get isolated SQL syntax error in SQLAlchemy

Using SQLAlchemy I would like to isolate any SQL syntax errors. For instance..
try:
[row for row in db.execute(text("select * from userds"), **args)]
except ProgrammingError as error:
print(error)
I get
(psycopg2.ProgrammingError) relation "userds" does not exist
LINE 1: select * from userds
^
[SQL: 'select * from userds'] (Background on this error at: http://sqlalche.me/e/f405)
And I'm only interested in..
relation "userds" does not exist
Anyone know if this is possible?
I have found a solution to my question. You must catch StatementError and print out the orig attribute on the error object, like so..
from sqlalchemy.exc import StatementError
try:
[r for r in db.execute("invalid statement")]
except StatementError as error:
print(error.orig)
https://github.com/zzzeek/sqlalchemy/blob/699272e4dcb9aa71ebbc0d9487fb6de82d3abc2b/lib/sqlalchemy/exc.py#L280

syntax error in select from where mysql statement

I got an syntax error in this code:
msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME = %s ;")
if cursor.execute(msql,name):
return True
else:
return False
i got an error near '%s'
can anybody tell me wherE? thanks!
error:
mysql.connector.errors.ProgrammingError: 1064(42000): You have an error in SQL syntax: check Mysql server version for the right syntax to use near '%s' at line 1 Im using mysql 5.6
Now I try this:
msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME='HCTC3153_INF.TXT'; ")
if cursor.execute(msql):
print "its is in the db"
return True
else:
print "its not in db"
return False
Always return its not in db even is in there...
The error raise now is:
raise errors.InternalError("Unread result found.")
mysql.connector.errors.InternalError: Unread result found.
Firstly I assume you are using %s for string formatting and not just a file with name %s.
I think you need to use '%s', not %s as in
msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME ='%s'")
Sorry if I misunderstood the use of %s completely
msql=("SELECT FILE_NAME FROM file_processed WHERE FILE_NAME LIKE '%s'")
try this dnt need to put ; near %s
I did
enter code here
got this!!
The answer to the first error, which I assume looks like:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s'
Is because cursor.execute() expects a tuple in the second argument, as explained by #mata in this SO post. In your case, your code should be cursor.execute(mysql,(name,)) - notice the comma after name.
I think you're receiving your second error:
mysql.connector.errors.InternalError: Unread result found
because you aren't doing anything with the result. If you added a result = cursor.fetchall() in your if block your code should work.

How to get the MySQL type of error with PyMySQL?

I'm doing a Python application with MySQL and PyMySQL and I'd like to be able to know the number of the MySQL error when I get one so that I can do something different depending on it.
Is there a way to do that with a try-except statement or another way?
Any exception in Python has an args member that shows you how it was constructed. For example:
>>> e = Exception(1, 2, 3, 4)
>>> e.args
(1, 2, 3, 4)
For pymysql, they're always constructed with (errno, errorvalue). So:
try:
do_stuff()
except MySQLError as e:
print('Got error {!r}, errno is {}'.format(e, e.args[0]))
I'm not sure this is guaranteed by the documentation, but you can see how it works pretty easily from the source.
pymysql maps mysql errors to python errors according to the following table:
_map_error(ProgrammingError, ER.DB_CREATE_EXISTS, ER.SYNTAX_ERROR,
ER.PARSE_ERROR, ER.NO_SUCH_TABLE, ER.WRONG_DB_NAME,
ER.WRONG_TABLE_NAME, ER.FIELD_SPECIFIED_TWICE,
ER.INVALID_GROUP_FUNC_USE, ER.UNSUPPORTED_EXTENSION,
ER.TABLE_MUST_HAVE_COLUMNS, ER.CANT_DO_THIS_DURING_AN_TRANSACTION)
_map_error(DataError, ER.WARN_DATA_TRUNCATED, ER.WARN_NULL_TO_NOTNULL,
ER.WARN_DATA_OUT_OF_RANGE, ER.NO_DEFAULT, ER.PRIMARY_CANT_HAVE_NULL,
ER.DATA_TOO_LONG, ER.DATETIME_FUNCTION_OVERFLOW)
_map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW,
ER.NO_REFERENCED_ROW_2, ER.ROW_IS_REFERENCED, ER.ROW_IS_REFERENCED_2,
ER.CANNOT_ADD_FOREIGN, ER.BAD_NULL_ERROR)
_map_error(NotSupportedError, ER.WARNING_NOT_COMPLETE_ROLLBACK,
ER.NOT_SUPPORTED_YET, ER.FEATURE_DISABLED, ER.UNKNOWN_STORAGE_ENGINE)
_map_error(OperationalError, ER.DBACCESS_DENIED_ERROR, ER.ACCESS_DENIED_ERROR,
ER.CON_COUNT_ERROR, ER.TABLEACCESS_DENIED_ERROR,
ER.COLUMNACCESS_DENIED_ERROR)
if you want to catch the errors then you will need to catch ProgrammingError, DataError, IntegrityError, NotSupportedError, and OperationalError, individually. You can see specifically which mysql error was caught by coercing the exception to a string using str.
try:
#interact with pymysql
except ProgrammingError as e:
print "Caught a Programming Error:",
print e
for name, ddl in TABLES.iteritems():
try:
print("Creating table {}: ".format(name))
db.execute(ddl)
except pymysql.InternalError as error:
code, message = error.args
print ">>>>>>>>>>>>>", code, message
That's a start but loads of other errors exist eg. OperationalError

python cx_oracle delete stmt error [duplicate]

This question already has an answer here:
cx_oracle Error handling issue
(1 answer)
Closed 10 years ago.
I'm trying a delete a particular row from a table in a try except block but I get the following error
self.returnvals['ERROR_CD'] = error.code
AttributeError: 'str' object has no attribute 'code'
Code:
try:
# code deleting from a table
except cx_Oracle.DatabaseError, ex:
error, = ex.args
self.conn.rollback()
self.returnerr['ID'] = 0
self.returnerr['ERROR_CD'] = error.code
self.returnerr['ERROR_MSG'] = error.message
self.returnerr['TABLE_NAME'] = self.debug_val
Your exception handling is broken. You're getting some sort of error oracle database error thrown inside your try block and it would be useful to see it, but the line in your code
self.returnerr['ERROR_CD'] = error.code
is throwing the error you're reporting because the "error" object is just a string and doesn't have a .code attribute.
Also...
delete from a table
Doesn't look like the actual DML you are attempting. Why don't you post the actual DELETE statement and maybe we can see if there's a syntax error. If this is your literal code, you need to read the documentation. I believe it's supposed to look more like:
import cx_Oracle as db
conn = db.connection()
cur = conn.cursor()
cur.execute("DELETE FROM TABLE WHERE somecolumn = someval")
conn.commit()
conn.close

pass table name as parameter in postgres via python

I want to execute postgres query in python.The table name has to be passed as a parameter.Since the table will be created at run time. I have used dict query param style.But i am getting an error.
import psycopg2
CONNECTION_STRING = "dbname='autogist' user='postgres' password=''"
query = "INSERT INTO %(table)s " +\
"(vin_id, vin_details_id, price, mileage, dealer_id, created_on, modified_on) " +\
"VALUES (%(vin_id)s, %(vlookup_id)s, %(price)s, %(mileage)s, %(dealer_id)s,now(),now()) " +\
"RETURNING id"
params = {"table" : "dealer_vehicle_details_2010_01_02",\
"vin_id":"3",\
"vlookup_id":"403",\
"price":"403",\
"mileage":"403",\
"dealer_id":"276092"
}
conn=psycopg2.connect(CONNECTION_STRING)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query,params)
TRACEBACK:
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (262, 0))
---------------------------------------------------------------------------
ProgrammingError Traceback (most recent call last)
/home/gridlex/workspace/<ipython console> in <module>()
/usr/local/lib/python2.6/dist-packages/psycopg2/extras.pyc in execute(self, query, vars)
121 self.index = {}
122 self._query_executed = 1
--> 123 return _cursor.execute(self, query, vars)
124
125 def callproc(self, procname, vars=None):
ProgrammingError: syntax error at or near "E'dealer_vehicle_details_2010_01_02'"
LINE 1: INSERT INTO E'dealer_vehicle_details_2010_01_02' (vin_id, vi...
The statement you send must be syntactically valid when PREPAREd, which a statement with placeholders for table names is not. You can't use placeholders for table names in prepared statements.
Your options are:
Substitute the table name in with regular string substitution, "double quoted". Be very careful with your quoting routine; make sure it doubles any quotes within the table name its self, so the table name double"quote becomes "double""quote". Eg. 'SELECT * FROM "%s"' % quote_ident(tablename). You'd have to roll your own quote_ident as AFAIK psycopg2 doesn't expose a function like that.
Send the table name as a query parameter to a PL/PgSQL function that uses EXECUTE ... USING to create a dynamic SQL statement using the table name. PL/PgSQL can use the quote_ident function to provide safer quoting than a home-rolled implementation.

Categories