Using dynamic SQL statement in Python 3 - python

I have a SQL statement to use in a MySQL database in my Python3 code. The code is as follows:
price = "1"
high = "2"
low = "3"
mycursor.execute("""
UPDATE
currency_price_fact
SET
%s = %s,
%s = %s,
%s = %s
WHERE currency_symbol = 'USD_gov'
""",(price,dict["USD_gov"]["p"].replace(",",""),high,dict["USD_gov"]["h"].replace(",",""),low,dict["USD_gov"]["l"].replace(",",""),))
But i am getting an error saying
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
I think i know what is going on here, i am passing '1' = '4432' instead of 1 = '4432' but i do not know how to solve it.

Related

How can you insert data to sql realtion using python dictionary(data-type),

lis = {'mno': 1, 200000:2}
query = """
insert into one values(%s, %s);
"""
cus.execute(query, lis)
a = cus.fetchall()
Where is error in this code?
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, %s)' at line 1

Python-MySQL prepared statement error while selecting where a value IS NULL

I want to select rows where a value is null but I get this error on executing using Python-MySQL prepared statement.
mysql.connector.errors.InterfaceError: 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 '?' at line 1
import mysql.connector
connection = mysql.connector.connect(database="XXXXX", user="XXXXX", password="XXXXX", host="XXXXX")
cursor = connection.cursor(prepared=True)
parameters = ["Ahmed", None]
statement = "SELECT * FROM Persons WHERE name_first = ? AND start_date IS ?"
cursor.execute(statement, tuple(parameters))

How to write proper MySQL Insert statement in Python?

I am trying to insert two columns of data into a MySQL table from Python. And my Insert statement is true, I guess. But I am still getting 1064 error code.
This is for MySQL server version 8.0.12 and Python 3.7. I had tried changing different methods of inserting dynamic variables.
#alter is the data value read from serial port
sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
print('Number of rows - ',cur.rowcount)
else:
print('No data in table')
for row in records:
print(row)
if row[1]==alter:
print("Student exists : ",row[1])
date = datetime.datetime.now()
print(type(date))
ins = (alter, date)
sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
cur.execute(sql, ins)
cnn.commit()
print('Sucessfully Stored the Record')
#success(alter)
break
else:
print("Student doesn't exist")
I am getting this error message
Error:
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 ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' at line 1
And I am expecting that these read tag values are inserted successfully​.
Identifiers (e.g. column and table names) in MySQL (and most other flavors of SQL as well) do not take single quotes. They take either no quotes, double quotes, or maybe backticks in the case of MySQL. Try this version:
sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
ins = (alter, date)
cur.execute(sql, ins)
cnn.commit()

mysql.connector.errors.ProgrammingError: Error in SQL Syntax

I'm using the Python MySQL connector to add data to a table by updating the row. A user enters a serial number, and then the row with the serial number is added. I keep getting a SQL syntax error and I can't figure out what it is.
query = ("UPDATE `items` SET salesInfo = %s, shippingDate = %s, warrantyExpiration = %s, item = %s, WHERE serialNum = %s")
cursor.execute(query, (info, shipDate, warranty, name, sn, ))
conn.commit()
Error:
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 'WHERE serialNum = '1B0000021A974726'' at line 1
"1B0000021A974726" is a serial number inputted by the user and it is already present in the table.
No , before the WHERE statement

Python unicode excape underscore and double quotes

I have data which represent usernames from different languages. I have carries out proper unicoding process as follows:
while attempts < 3 and not success:
query = ur'''select gu_name from globaluser where gu_name = "{uname}"'''.format(uname=unicode(filerow['user_name'],'utf-8', errors='strict'))
try:
self.gdbCursor.execute(query.encode('utf-8'))
gUser = self.gdbCursor.fetchone()
But when it comes to names like this Name1_"GG"_Name1AnotherName I ended up getting following error:
ProgrammingError: (1064, '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 \'GG" Cooper"\' at line 1')
How do I properly encode these type of characters?
Update:
Based on the answers provided I did the following:
\'GG" Cooper"\' to resolve user name
while attempts < 3 and not success:
#query = ur'''select gu_name from globaluser where gu_name = "{uname}"'''.format(uname=unicode(filerow['user_name'],'utf-8', errors='strict'))
uName = unicode(filerow['user_name'], 'utf-8')
query = ur'''select gu_name from globaluser where gu_name = "%s"'''
try:
#self.gdbCursor.execute(query.encode('utf-8'))
self.gdbCursor.execute((query % (uName)).encode('utf-8'))
gUser = self.gdbCursor.fetchone()
But I still get the following error:
ProgrammingError: (1064, '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 \'GG" Cooper"\' at line 1')
You should be using parameters inputs as it suggested in:
http://legacy.python.org/dev/peps/pep-0249/#id15
Here is an example:
sql = "insert into foo values(%s)"
cursor.execute(sql, ('My very %$#*#"""S weird name',))

Categories