Similar to Brunonono in Create MySQL Database in Python using the %s operator (even using the same packages) I'm trying to add columns from an excel table to a mysql table using the %s operator in Python. The error is the same:
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 %s)' at line 1
The code is as follows
mydb=mysql.connector.connect(host="localhost",user="root")
#init cursor
mycursor=mydb.cursor()
column_title="ID"
cell_type="INT(10)"
mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type)
Sadly, I wouldn't know how to apply the solution provided in the post above, where
mycursor.execute("CREATE DATABASE (%s)", (db_name))
was replaced with
create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)
mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type) is what you are doing currently
Instead do,
mycursor.execute("ALTER TABLE Test ADD (%s %s)" % (column_title, cell_type))
Which would work unless I don't know MySQL syntax properly
Try this:
mycursor.execute('ALTER TABLE Test ADD (?, ?)',(column_title, cell_type))
But this doesn't use the %s operator.
Sorry, this works for SQLite and not MySQL.
Related
I'm using Python + MySQL and want to use parameterized query. I'm stuck. I've encountered an error and can't figure out how to solve it. I've spent a day, checked dozens of articles, used various options (sinle quotes, double quotes, prepared statements) and still no luck.
Requirements: use Parameterized Query
Here is basic demo of the issue:
#!/usr/bin/python3
import mysql.connector as mysql
conn = mysql.connect(host=server, user=username, passwd=password, autocommit=True)
try:
create_database_query = "CREATE DATABASE %s;"
db_name = "BOOKS"
cursor = conn.cursor()
print(f"Creating {db_name} database... ", end='')
cursor.execute(create_database_query, (db_name,))
print("Success")
except mysql.Error as error:
print("Parameterized query failed {}".format(error))
Output:
Creating BOOKS database... Parameterized query failed 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 ''BOOKS'' at line 1
So it looks like it uses too many quotes (2 single quotes on each side). The code above works fine if I change the following line:
create_database_query = "CREATE DATABASE %s;"
and put backtick around %s
The problem that now it creates a database but with invalid chars - 'BOOKS' (quotes are now part of db name). Duh...
If I use prepared statements then the same issue occurs but slightly different error message:
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 '?' at line 1
Environment:
MacOS Catalina
Python 3.8
PyCharm 2019.3 IDE
MySQL 8.0.19
mysql-connector-python module 8.0.19
What is going on? Any ideas?
Thanks
You can't use query parameters for identifiers (like a database name or table name or column name).
Query parameters can be used only in place of a constant value — a quoted string, quoted date/time, or a numeric value. Not identifiers, expressions, SQL keywords, etc.
To combine a database name with your CREATE DATABASE statement, you have to format it into the string in a way that forms the full statement before it is sent to MySQL.
db_name = "BOOKS"
create_database_query = "CREATE DATABASE %s;" % db_name
cursor.execute(create_database_query)
Because this creates a risk of SQL injection when you format variables into your string, it's up to you to make sure the db_name is safe.
Update: Thanks to #Parfait for the reminder about current best practices of string-formatting.
Prefer:
db_name = "BOOKS"
create_database_query = "CREATE DATABASE {};".format(db_name)
Or F-strings:
db_name = "BOOKS"
create_database_query = f"CREATE DATABASE {db_name};"
(In other words, Python has become Ruby ;-)
I am having some trouble selecting from my database using python to execute a MySql query. I have tried two methods to achieve this, but both methods have returned the error shown below:
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
What Id like to do is return the row count (which is always zero or one) when a username parameter is passed. I have looked at other examples where people have had this issue but I cant find a good fix.
The first method I tried was this:
def check_data(username):
sql = """SELECT count(*) FROM tbl_user WHERE username = %s"""
mycursor.execute(sql, username)
#do something with the data
I then tried using SELECT (CASE WHEN (uname = %s) THEN TRUE ELSE FALSE END) AS IsEmtpy FROM tbl_user limit 1;
This works database side, but still throws the same error when run in the application. I tried wrapping the %s like '%s' but it didn't help.
Any suggestions?
You're missing enclosing the string between quotes (singles or doubles).
You can check the query you're executing by printing it before the mycursor.execute statement, but basically you're sending MySQL something like SELECT count(*) FROM tbl_user WHERE username = foobar.
Try fixing it with SELECT count(*) FROM tbl_user WHERE username = '%s'.
On a side note, your approach is vulnerable to SQL Injection. You should check the documentation of the tool you're using to connect to the DBMS for "prepared statements".
I'm trying to insert variables as data into a database
I'm using this (part of it)
query = "INSERT INTO table_name (name) VALUES (%S)"
aa="naam"
cursor.execute(query,aa)
and everytime, I get the following error message:
"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"
no matter what I try to do, I'm getting this message (put it in """, put () around it, ...)
Hope someone can help me
The format needs to be lowercase, so change the query into: query = "INSERT INTO table_name (name) VALUES (%s)".
Can't insert more than two data's in the mysql database i'm running the code in python using raspberry pi.
the code i used is
query="INSERT INTO import(customer,package) VALUES('%s','%s')"
cursor.execute(query,(name,data))
it gives an error to check the syntax.
You also need to add connection.commit() after your insert/update queries.
Example
connection = MySQLdb.connect(*data)
cursor = connection.cursor()
cursor.execute(<query>)
connection.commit()
When using parameters, you should not quote your parameters. That is, your query should be;
query="INSERT INTO import(customer,package) VALUES(%s, %s)"
I'm using python 2.7.3 and Sqlite3 to save some data in a small db. I have the following sql command:
thedb = "allpeople"
cursor.execute("INSERT INTO %s VALUES (?,?,?,?,?,?,?,?,?,?,?,?)" % (thedb, data))
conn.commit()
But its throwing the following error:
TypeError: not all arguments converted during string formatting
You are trying to insert the table name (not the database). You appear to be mixing that up with SQL parameters; string templating and providing SQL parameters for your query are two entirely separate operations.
You'd have to use string formatting separately to build the query string:
cursor.execute("INSERT INTO %s VALUES (?,?,?,?,?,?,?,?,?,?,?,?)" % thedb, data)
or perhaps a little clearer to illustrate what is going on:
query = "INSERT INTO %s VALUES (?,?,?,?,?,?,?,?,?,?,?,?)" % thedb
cursor.execute(query, data)
Note that this opens you up to a possible SQL injection vector. Perhaps you should look into a decent SQL library instead; SQLAlchemy lets you build SQL queries from Python calls (among other tasks).