1064: SQL syntax error executing PyMySQL query [duplicate] - python

This question already has answers here:
Using a Python variable in MySQL query
(2 answers)
Closed 4 years ago.
I am using PyMySQL to execute SQL query commands from python. My pystyle is pyformat which was found using:
>>> pymysql.paramstyle
pyformat
My db and cursor details are as follows:
>>> MYDB = pymysql.connect(_params_)
>>> cursor = MYDB.cursor()
I then execute a SQL query using,
>>> cursor.execute("SELECT * FROM %(tablename)s", {"tablename": "activity"})
I get an error stating,
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 '''activity''' at line 1")
On the other hand, the query by itself works,
>>> unsafe_sql = ("Select * from activity")
>>> cursor.execute(unsafe_sql)
>>> 4
I am not sure what is going on with my first query. Any help appreciated.

You can't pass a table name as a parameter to cursor.execute(). Whenever a parameter is a string it quotes it when it substitutes into the query. Use a normal string formatting method, e.g.
cursor.execute("SELECT * FROM %(tablename)s" % {"tablename": "activity"})

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?

PyMySQL table name placeholder

I know this has been asked a million times, but noone seems to provide an alternative...
So this doesn't work:
DW = pymysql.connect(...)
table = "myTable"
with DW.cursor() as cur:
cur.execute("SELECT * FROM %s", (table,)) # error here
data = cur.fetchall()
Error:
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 ''myTable'' at line 1")
psycopg2 for PostgreSQL has psycopg2.sql.Identifier or AsIs which basically removes the single quotes and acts as an identifier in the query...is there an equivalent for pymysql?
Also, other answers use string formatting and other methods that are vulnerable to SQL injection - this is something I want to avoid.

Trying to use a variable in a Python SQL Select Query [duplicate]

This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 12 months ago.
I am trying to search a database filtering by a category which the user chooses and selects. I have attempted to add a Variable into my Select Query but it keeps failing with a SQL syntax error but I cannot find any syntax issues
var1 = "World"
selectQ = """SELECT name, score FROM score WHERE category = %s"""
cursor.execute(selectQ, Var1)
The Error is 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' at line 1
You can try below,
var1 = "World"
cursor.execute("SELECT name, score FROM score WHERE category = %s", (var1))
Note, the parameters should be passed as tuple.

Python mysql parameters and load data command [duplicate]

This question already has an answer here:
Python sqlite3 parameterized drop table
(1 answer)
Closed 5 years ago.
I'm trying to use a variable for a table name. I get the error "... near ''myTable'' at line 1
I must not be escaping this right. The double '' in the error seems to be a clue, but I don't get it.
db = MySQLdb.connect("localhost","user","pw","database" )
table = "myTable"
def geno_order(db, table):
cursor = db.cursor() # prepare a cursor object using cursor() method
sql = "SELECT * FROM %s"
cursor.execute(sql, table)
results = cursor.fetchall()
You can't use a parameter for the table name in the execute call. You'll need to use normal Python string interpolation for that:
sql = "SELECT * FROM %s" % table
cursor.execute(sql)
Naturally, you'll need to be extra careful if the table name is coming from user input. To mitigate SQL injection, validate the table name against a list of valid names.

Python MySQLdb execute table variable [duplicate]

This question already has an answer here:
Python sqlite3 parameterized drop table
(1 answer)
Closed 5 years ago.
I'm trying to use a variable for a table name. I get the error "... near ''myTable'' at line 1
I must not be escaping this right. The double '' in the error seems to be a clue, but I don't get it.
db = MySQLdb.connect("localhost","user","pw","database" )
table = "myTable"
def geno_order(db, table):
cursor = db.cursor() # prepare a cursor object using cursor() method
sql = "SELECT * FROM %s"
cursor.execute(sql, table)
results = cursor.fetchall()
You can't use a parameter for the table name in the execute call. You'll need to use normal Python string interpolation for that:
sql = "SELECT * FROM %s" % table
cursor.execute(sql)
Naturally, you'll need to be extra careful if the table name is coming from user input. To mitigate SQL injection, validate the table name against a list of valid names.

Categories