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()
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))
I have the following sample Python code, and when I try to execute, am getting mysql error message. Context, am trying to create custom logs, log the messages, insert to a MySql table for analysis. Providing relevant portions for mysql execute.
levelnum= str(record.levelno) # 40
levelname=str(record.levelname) # ERROR
msg=str(self.log_msg) # "This error occurred: This is test message"
createtime=str(tm) #2018-06-26 03:43:47
record.name = 'MY_LOGGER'
sql = 'INSERT INTO emp.log (log_level, log_levelname, log, created_at, created_by) VALUES ('+levelnum+ ', '+levelname+ ', '+msg+ ', '+createtime+ ', '+record.name+')'
Error message: ProgrammingError: (1064, u"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 'error msg, 2018-06-26 03:43:47, MY_LOGGER)' at line 1")
Am using mysql, and trying to insert to the table as follows:
try:
self.sql_cursor.execute(sql)
self.sql_conn.commit()
except pymysql.InternalError as e:
print e
print 'CRITICAL DB ERROR! Logging to database not possible!'
I think, am missing some formatting while passing parameters in the SQL query, but couldn't get the correct one.
Appreciate if someone can help fix this.
You are not quoting the timestamp, hence the error.
Rather than trying to quote the values manually, use the built-in quoting functionality provided by pymysql as part of the DBI interface.
sql = 'INSERT INTO `emp.log` (`log_level`, `log_levelname`, `log`, `created_at`, `created_by`) VALUES (%s, %s, %s, %s, %s)'
self.cursor.execute(sql, (levelnum, levelname, msg, createtime, record.name))
I keep getting the error: "'builtin_function_or_method' object has no attribute 'execute'" I originally thought the complaint was on the table value function in SQL Server, however, I see that the message points to "execute", so I don't think refcur has execute defined. Here's what my connection string looks like:
conn = pyodbc.connect("Driver={SQL Server};"
"Server=myserver;"
"Database=mydatabase;"
"Trusted_Connection=yes;"
"autocommit=True;")
refcur = conn.cursor
sql = "exec myschema.mystoredproc #TVPobject=?"
refcur.execute(sql,this_object)
I've attached the image to show what I see in intellisense for what's available. Does anyone know why this is happening?
you aren't calling cursor, you're just returning a reference to that member function and storing it in refcur. In order to call it (and actually create a cursor), you need to add parenthesis:
refcur = conn.cursor()
# Here -------------^
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',))