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.
Related
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?
This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 4 months ago.
I want to run the following code, but Python gives me an error
code :
select = input("ENTER USER FOR PASS RECOVERY : ")
cursor.execute("SELECT COUNT(*) FROM user_stat WHERE usr=(%s)",(select))
python code
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 '%s)' at line 1
error picture
In which part of the code is the problem and what should I do?
The second argument to cursor.execute must be an iterable of params, So you should pass them as:
A list: [select]
A tuple: (select, ). Note that passing (select) does not make it a tuple.
And another question, which client do you use to connect to MySQL? Some clients use ? as param placeholders and not %s
if you need more examples or more help similar post is here -> How to use variables in SQL statement in Python?
Also take a look at Kashyap (https://stackoverflow.com/a/21734918/2561174) comment with a good/bad query practices, he give this example on how to use it:
# Do this instead
t = ('RHAT',)
cur.execute('SELECT * FROM stocks WHERE symbol=?', t)
Wish it helps you!
You have to use {} instead of ()
select = input("ENTER USER FOR PASS RECOVERY : ")
cursor.execute("SELECT COUNT(*) FROM user_stat WHERE usr={%s}",(select))
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.
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"})
This question already has answers here:
Variable table name in sqlite
(9 answers)
Closed 6 years ago.
I have a program where the user can select what table they want to modify in SQLite. I store the selection in a variable called table, then try and select everything from that table
c.execute('SELECT * FROM ?', (table,))
The program gets stuck at the question mark. It says:
"Sqlite3.OperationalError: near "?": syntax error"
What am I doing wrong?
You can't use parameter substitution for the table name. You need to add the table name to the query string yourself. Something like this:
query = 'SELECT * FROM {}'.format(table)
c.execute(query)
One thing to be mindful of is the source of the value for the table name. If that comes from an untrusted source, e.g. a user, then you need to validate the table name to avoid potential SQL injection attacks. One way might be to construct a parameterised query that looks up the table name from the DB catalogue:
import sqlite3
def exists_table(db, name):
query = "SELECT 1 FROM sqlite_master WHERE type='table' and name = ?"
return db.execute(query, (name,)).fetchone() is not None