Python pymySQL string quotes - python

I am trying to insert a string
insert_cmd = "INSERT INTO inv values (\""+str(row[1])+"\",\""+str(row[2])+"\")
(cur.execute(insert_cmd))
Error Message:
pymysql.err.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 \'google search appliance"","active","D\' at line 1')

Better to use query parameters to avoid quoting and other issues:
cur.execute("INSERT INTO inv values (%s, %s)", (str(row[1]), str(row[2])))
It's also a best practice to name your columns in case your model changes later:
"INSERT INTO inv (col1, col2) VALUES (%s, %s)"

Related

You have an error in your SQL syntax error appearing with correct syntax [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 28 days ago.
I am making an app in python flask, and I executed a sql query. I am using Mysql server 8.0.
My code is:
mydb = mysql.connector.connect(
host="localhost",
user="...",
password=".....",
database="....."
)
cursor = mydb.cursor()
sql = "INSERT INTO calender_events (class,date,title,desc) VALUES (%s, %s ,%s, %s)"
val = (str(student_class), str(date.today()),title,desc)
cursor.execute(sql, val)
mydb.commit()
I get the 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 'desc) VALUES ('8a', '2023-01-23' ,'er', 'er')' at line 1
although my syntax is correct, I think. I do not know my this error is occuring. Any help would be greatly appreciated. Thanks!
This is because desc is a reserved word in MySQL. See this question, which shows you should use
sql = "INSERT INTO calender_events (class,date,title,`desc`) VALUES (%s, %s ,%s, %s)"
note the backticks around desc. Alternatively, you could use a different name for this column, maybe description?

Inserting variable values into MySQL database; I'm using (%s) but getting syntax error

table name: 'tickers_list' (table has only 1 column)
column name: 'Ticker'
The following works:
sql = "INSERT INTO tickers_list (Ticker) VALUES ('AAPL')"
mycursor.execute(sql)
mydb.commit()
But when I try to set it up to accept variables, it's not working:
symbol = 'AAPL'
sql = "INSERT INTO tickers_list (Ticker) VALUES (%s)"
mycursor.execute(sql, symbol)
mydb.commit()
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)' at line 1
Where am I going wrong?
You need to execute with a tuple, and a tuple must contain at least one ,. In Python for a single value this means:
mycursor.execute(sql, (symbol,))
Which does look a bit weird, but it's just how it is. For multiple values it looks more normal, no trailing , is necessary.
In addition to what tadman says, strings need quotes:
... ("%s") ...

Python 2.7 to MariaDB SQL error

I'm trying to insert data into a sequel table using variables. The following statement is the one causing errors:
cursor.execute("INSERT INTO %s (avg_time,max_time) VALUES (%s,%s)", (SOURCE, reav, remax))
The error is:
_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 ''USA' (avg_time,max_time)
VALUES ('6.997','7.071')' at line 1")
Anyone know where I've gone wrong?
Change this:
cursor.execute("INSERT INTO %s (avg_time,max_time) VALUES (%s,%s)", (SOURCE, reav, remax))
To this:
cursor.execute("INSERT INTO %s (avg_time,max_time) VALUES (%%s,%%s)" % SOURCE, (reav, remax))
Found here
Although this would seem to be prone to SQL injection with the table name given it's using string formatting.

mysql.connector.errors.ProgrammingError: 1064 (4200): You have an error in your SQL syntax;

I am attempting to insert data into a MySQL database. I am using python 2.7 and I am using the mysql.connector.
My error is:
mysql.connector.errors.ProgrammingError: 1064 (4200): 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) at line 1.
This indicates a error in my code where I attempt to insert my variable np (VALUES (%s)");). np is a "noun-phrase" such as a "skate board".
import mysql.connector
from textblob import TextBlob
cnx = mysql.connector.connect(user='XXX', password='XXX',
host='XXXXX',
database='XXXX')
cursor = cnx.cursor(buffered=True)
Latest = ("SELECT * FROM SentAnalysis")
cursor.execute(Latest)
for row in cursor.fetchall():
SentText = row[2]
blob = TextBlob(SentText)
for np in blob.noun_phrases:
print(np)
SQLInsertCmd = ("INSERT INTO TestNounPhrase (NPhrase) VALUES (%s)")
cursor.execute(SQLInsertCmd,np)
cnx.commit()
cursor.close()
cnx.close()
The example from the manual is https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html. e.g.
"VALUES (%s, %s, %s, %s, %s)")
I can't see a difference. This error is also discussed in detail here : How can I fix MySQL error #1064? Other similar examples on stackoverflow have been linked to reserved words, Redundant comas .But looking at these examples I can't spot an obvious error.
Any suggestions on where I am going wrong would be much appreciated.
I think the issue here might be the semicolon at the end of the query.
Have a good day.
str parameter in SQL query must by in quote 'str'.
So, need use '%s' with ' ' for str, and %s without ' ' for numbers:
cursor.execute("""INSERT INTO db_name (str,int,str,int)
VALUES ('%s', %s, '%s', %s)""" % (str,int,str,int))
cnx.commit()
You have to convert the tuple which contains the value to insert into a 'full tuple'.
e.g.:
for np in blob.noun_phrases:
np=(np,)
In a generic example, if you just have one column to insert, it would be:
to_insert=('A value to insert',)
Lastly, if you had multiple values to insert at a time:
to_insert_multiple=[('value1',), ('value2',), ('valueN',)]
I hope it helps, it worked for me in py3.7
Try this
SQLInsertCmd = """INSERT INTO
TestNounPhrase (NPhrase) VALUES ((%s))""" % (np)
cursor.execute(SQLInsertCmd)
I'm a little late for this post but here is my solution for this.
I'm using py 3.10
I think this error comes because of using/passing string to cursor, to avoid this we can use tuple as pointed out by some answers above.
from mysql import connector
cnx = connector.connect(**config)
cursor = cnx.cursor(buffered=True)
YOUR_VALUES = (FIELD_NAME_1,FIELD_NAME_2,...)
query = f"INSERT INTO `TABLENAME` (`FIELD_NAME_1`, `FIELD_NAME_2`) VALUES
{VAL}"
cursor.execute(query)
cnx.commit()
cnx.close()
I had the same issue with the single parameter statement, this worked:
mycursor.execute("INSERT INTO cust (user) VALUES(%s)" % (username))
I was getting same error and while searching for its solution I stumbled upon this question after several attempts I was able to resolve. The mistake was a typing error for column name in WHERE clause of UPDATE statement. My column name was 'ROLL_NO' instead I had typed 'ROLL_NO.'
Please look to this point as well.
when calling the execute() method:
cursor.execute(query, (param))
should be:
cursor.execute(query, (param,))
I had a quite a struggle with this error because one of the column-name was exit. Be aware that database will accept this as a column name but when you try to insert from python, you need to cover the column in with backticks `
you should give %s value like this:
"INSERT INTO LaptopPrice (Name) VALUES ('%s')" % value
if you have few values you have to use tuple of your valuse like this code:
"INSERT INTO LaptopPrice (Name, Price, Size, Weight, ScreenSize, Resolution, CPU, RAM, RAMType, Memory, MemoryType, GraphicCard) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % tuple(values)
mycursor.execute("insert into table_name(column) values(%s)"%data_variable)

Programming Error in python, How do I parse values of a tuple in a table with SQL query?

In order to parse the values of variables a and b in the field username and password respectively of table admin_details I tried this method the pseudo code is something like below:
...
...
a=4
b=8
....
....
cur.execute("INSERT INTO admin_details(username, password) VALUES('%s','%s'), %(a,b)")
....
I get the value inserted in the table as username: 4 password:8
But in order to insert the characters like** a=' john' b='snow'in the admin_details field.
I tried using tuples as below
a='john'
b='snow'
tup=['a','b']
and to insert this tuple's value a and b in the table i tried all the possible ways but still I am not able to store the variables in the table.
cur.execute("INSERT INTO admin_details(username, password) VALUES('%s','%s'), % ['a','b']")
But I get this
_mysql_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 'INTO INTO admin_details(username) VALUES('%s'), %('entry1.get()')' at line 1")
Do not attempt to use string formatting for constructing SQL queries. Pass query parameters in the second argument to execute() - this way you'll protect yourself against sql injection problems:
a = 'john'
b = 'snow'
cur.execute("INSERT INTO admin_details(username, password) VALUES(%s, %s)", (a, b))
Note that in this case you also don't need quotes around the placeholders in the query.
See also:
Python MySQL Parameterized Queries
I think use this way to insert mysql data should be better:
insert_sql = 'INSERT INTO admin_details(username, password) VALUES("{0}","{1}")'.format(*tup)
cur.execute(insert_sql)
conn.commit()

Categories