Python unicode excape underscore and double quotes - python

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',))

Related

MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versi [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 1 year ago.
I am trying to insert data into a MySQL table using my Flask app as shown below;
#Create MySQL connection and write data into the table user_data from the POST form
sql_cursor = mysql.connection.cursor()
sql_cursor.execute("""INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value)
VALUES (new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],
add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_value);""")
mysql.connection.commit()
sql_cursor.close()
This does not work too:
sql_cursor = mysql.connection.cursor()
sql_cursor.execute("INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_value))
mysql.connection.commit()
sql_cursor.close()
I get the below error:
I get the below error:
MySQLdb._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 'condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value)\n ' at line 1")
Someone please help me.
The homepage explains how to use placeholders https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
If your variables are all valid.
this should work
sql_cursor.execute("""INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value)"""\
""" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, %s);""",(new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],
add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_valu)))
mysql.connection.commit()
sql_cursor.close()
Apparently, your connection driver is not configured to accept line breaks \n, try change your template string using concatenation or all inline statement...
sql_cursor = mysql.connection.cursor()
sql_cursor.execute("""INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value) VALUES (new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_value);""")
mysql.connection.commit()
sql_cursor.close()

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))

1064 error while operating MySQL database with Python

I want to write a program in Python to control MySQL database, but the following error occurs
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; chec
k the manual that corresponds to your MySQL server version for the right syntax
to use near 'Code,type, number,Whether )VALUES ('cl8k-k520-fg45-d4sa-sd9k','n' at line 1")
Codeļ¼š
import pymysql
db = pymysql.connect("localhost", "root", "root", "test")
cursor = db.cursor()
sql = "INSERT INTO BOOKS(Activation Code, \
type, number,Whether ) \
VALUES (%s,%s,%s,%s)"
data = [("cl8k-k520-fg45-d4sa-sd9k",'n','10','n'),
("jhg6-58jh-gh8o-8uik-7jk8",'c','20','n'),
("x5hg-gf5h-4hj5-g4h5-fh5t",'y','999','n'),
("fg8j-h584-fd4g-fg4d-fgg4",'n','1','y'),
("4jk4-5kl4-4klk-4lji-4ghj",'e','6','n'),
]
cursor.executemany(sql,data)
db.close()
This is my first time to ask questions on this platform. I hope to get answers
enclose Activation Code as 'Activation Code'

Using dynamic SQL statement in Python 3

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.

MySQLdb Module Python error

I have this method of an object that read all the table present in a database and returns the query's result.
def get_tables(self):
self.__cursor.execute('SELECT table_name FROM information_schema.tables where table_schema="{}";)'.format(self.__database))
query_result = self.__cursor.fetchall()
if not self.__cursor.rowcount:
return False
else:
return query_result
The method is call from it:
query_result = get_tables()
for record in query_result:
print record[0]
When i execute the script, i see in the console the result that i want and at the end this error:
Exception _mysql_exceptions.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 ')' at line 1") in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x7fbd06161910>> ignored
How can i resolve it?
Your SQL is broken:
... table_schema="{}";)
Remove the trailing ).

Categories