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.
Related
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", ))
In Visual Basic, there is an inherited base object that is effective for error debugging purposes. Is there an equivalent for the "Err" object in Python?
Dim Msg As String
' If an error occurs, construct an error message.
On Error Resume Next ' Defer error handling.
Err.Clear
Err.Raise(6) ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & ControlChars.CrLf & Err.Description
MsgBox(Msg, MsgBoxStyle.Information, "Error")
End If
For example:
def exec_sproc(sql,cnxn):
try:
cursor=cnxn.cursor()
cursor.execute(sql)
cnxn.commit()
cursor.close()
except(err):
print("error: {0}".format(err))
There is a suggestion to try
except Exception,e: print str(e)
I get an invalid syntax because 'e' is not defined or in the former example err shows as invalid syntax.
What is the base error object in Python? In most examples, user-defined custom errors are demonstrated rather than coding a return of the actual "Python" error. If I know what the error is, I prefer not to make it. Instead, show me what Python sees as the error. (anything other than invalid syntax would help)
I guess this is what you are looking for
def exec_sproc(sql,cnxn):
try:
cursor=cnxn.cursor()
cursor.execute(sql)
cnxn.commit()
cursor.close()
except Exception as err:
print("error: {0}".format(err))
for more on Python exceptions look here
I'm new to sql so maybe this is just a beginner's mistake, but after trying some solutions I found here and there I'm still unable to solve this problem. I'm trying to upload an image to a mariadb database through a python script which looks like this:
import mysql.connector
path=input("File to upload: ")
with open(path,'rb') as f:
fileData=f.read()
query=f"UPDATE emp SET image={fileData} WHERE empId=1;"
db=mysql.connector.connect(...)
myCursor=db.cursor()
myCursor.execute(query)
myCursor.close()
db.close()
print(f"Uploaded {path} to the database...")
However, when the code reaches myCursor.execute(query) I get the following error:
Traceback (most recent call last):
File "webSqlSampleClient.py", line 16, in <module>
myCursor.execute(query)
File "/home/asriel/.local/lib/python3.8/site-packages/mysql/connector/cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/home/asriel/.local/lib/python3.8/site-packages/mysql/connector/connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/home/asriel/.local/lib/python3.8/site-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
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 'b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xe1\x00'' at line 1
What's wrong with my code? The rest of the query seems correct as I've used the very same UPDATE statement with other non-image values successfully.
Thank you in advance for the help.
-Update:
As #tadman suggested, I've used %s as a placeholder in my sql query, so the new code looks like this:
query="UPDATE emp SET image=%s WHERE empId=1"
db=mysql.connector.connect(...)
myCursor=db.cursor()
myCursor.execute(query, (fileData,))
myCursor.close()
db.close()
The code above doesn't run into any exceptions and prints the intended output, however, when I execute the following SQL statement in my SQL client:
SELECT image
FROM emp
WHERE empId = 1;
it says that the value for image is NULL.
What's wrong now? image is a blob, in case that's not clear.
Ok, so I've just got it to work:
the answer I used to solve the first problem was #tadman's answer (which is in the question's comments). The problem I had with the database not updating its values was solved by adding db.commit() (I forgot that, silly mistake). Thanks for all of your helpful comments anyways!
hwid1 = str(subprocess.check_output(
'wmic csproduct get uuid')).split('\\r\\n')[1].strip('\\r').strip() # Get Hard Ware Id of the pc
def AutoUpdateDB():
SQL.execute(f"select hwid from Accounts WHERE hwid = {hwid1}")
result_user = SQL.fetchone()
print(result_user[0])
time.sleep(5555)
i am trying this code and its giving me error
i tried to solve this but its still not working
here is the error
psycopg2.errors.SyntaxError: syntax error at or near "C"
LINE 1: ...ect * from Accounts WHERE hwid = AD902276-A4F9-961C-492B-2CF...
<br/>^
Others have already pointed out why you are getting the specific error you are getting, but I would like to mention that the way around it is nearly always to use parametrized queries, i.e. something like
SQL.execute("SELECT hwid FROM Accounts WHERE hwid = %s", [hwid1])
This can save you no end of headaches if hwid1 contains "funny" characters.
I have an update statement in my database that is not executing. As far as I am aware, it is syntactically correct. I used this app to verify the syntax. The except block is all that is being executed and I do not understand why.
Here is the code:
for res_posts in list_of_response_ids:
temp_str = res_posts[0] # first element of res_posts tuple is string
temp_str += ":" + str(output[0])
try:
sql = "UPDATE POST SET res_post_id = %s WHERE post_id = %d;" % (str(temp_str), int(res_posts[1]))
cursor.execute(sql)
except:
print "uh oh"
I can post more code if this is not enough information.
EDIT: Following Jacob's advice, I used raise and got the following error:
Traceback (most recent call last):
File "post.cgi", line 93, in <module>
cursor.execute(sql)
File "/usr/lib64/python2.6/site-packages/MySQLdb/cursors.py", line 173, in execute
self.errorhandler(self, exc, value)
File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
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 ':37 WHERE post_id = 8' at line 1")
Thank you so much!
Based on your traceback, there is something wrong with the type of entry you are using for the res_post_id or post_id. Currently you are not passing a representation of the res_post_id string, but a literal string. If res_post_id is a string in your DB Schema, I would recommend using %r like so:
sql = "UPDATE POST SET res_post_id = %r WHERE post_id = %d;" % (str(temp_str), int(res_posts[1]))
This will properly quote your res_post_id value for insertion.
So your statement should change from this:
UPDATE POST SET res_post_id = :37 WHERE post_id = 8;
...to this:
UPDATE POST SET res_post_id = ':37' WHERE post_id = 8;