Python MySQL connector select with variable - python

I've this little query :
id = 'TESTID'
sql = "SELECT ID,PASSWORD FROM USERS WHERE ID = %s"
cursor.execute(sql,(id))
and i'm having 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 'TESTID''' at line 1
I know this is something about double quotes. I've multiple other query that runs perfectly, but they have like 3 parameters
example :
id = 'TESTID'
GR = 'TEST'
name = 'HELLO'
last_name = 'WORLD'
sql = "INSERT INTO USERS (ID,GR,name,last_name) VALUES (%s,%s,%s,%s)"
cursor.execute(sql,(id,gr,name,last_name))
This one don't have 3 double quote at the beginning and 3 others at the end and runs perfectly so i dont know what to do now.
Thanks you.

One thing you should remember in python is that (7) is the same as 7. For a tuple of length 1, you have to say (7,) (note that important trailing comma).
So change this line:
cursor.execute(sql,(id)) to cursor.execute(sql,(id,)).

Related

LIKE Command in SQL

I tried to write a query with Like command to search for special Name , but i need to get the value from User and i need to read the value but my sql code has problem with "LIKE" section , how can i fix it ?
sql = '''SELECT Name FROM newtest WHERE Name LIKE = %s'''
val = (n)
myobj = mycurs.execute(sql , val)
what's the problem ?
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 '= %s' at line 1
this is the error
Remove the "=" sign. The LIKE command doesn't use that - see https://www.w3schools.com/sql/sql_ref_like.asp for an example.
If you need to search for non-exact matches (i.e. the name is anywhere inside the column) you can change the query as:
SELECT Name FROM newtest WHERE Name LIKE concat('%', %s, '%')

Create MariaDB database with Python

I would like to write a python script to create new MariaDB databases.
The database name is a user input. I tried to use arguments for creating the database:
#!/usr/bin/python3
import mysql.connector
mariadb_host = '127.0.0.1'
mariadb_port = 3306
mariadb_user = 'root'
mariadb_password = 'password'
mariadb_connection = mysql.connector.connect(
host=mariadb_host,
port=mariadb_port,
user=mariadb_user,
passwd=mariadb_password,
use_pure=True
)
query = 'CREATE DATABASE %(db_name)s;'
args = {'db_name': 'test-db'}
result = None
cursor = mariadb_connection.cursor()
cursor.execute(query, args)
print(cursor.statement)
result = cursor.fetchall()
cursor.close()
The following error appears: mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''test-db'' at line 1
It seems, that the command cursor.execute appends ' around the database name, which results in an invalid sql query.
How could I get around this problem and create safely new database from user input?
Parameter substitution notation - %(name)s or just %s is for interpolating values into an SQL statement.
RDBMSs have different quoting rules for values and identifiers like database, table or column names. For example, a string value will be surrounded by single quotes to tell the RDBMS that is is a character value, but single-quoting an identifier is a syntax error; the RDBMS will require that identifiers are quoted using some other character (for example backticks, double-quotes, square brackets, depending on the RDBMS).
If you want to interpolate identifiers using Python you have to use string formatting techniques. For example, using an f-string
db_name = 'test-db'
query = f'CREATE DATABASE `{db_name}`;'
Note that it is best to quote dynamic identifier names with backticks to handle names which contain special characters.
As always with dynamic SQL generation, you should be aware of the risk of SQL injection when handling data from an untrusted source.

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") ...

Receiving error from sql, is it the sql command itself or something else entirely?

I'm resorting to overflow as a last ditch effort. I have been facing this bug for an incredibly long time and I have had no luck. I will try anything.
My sql command is
update_query = """
UPDATE users_data
SET stocks = """+str(stock)+"""
WHERE id = """+str(userid)
cursor = connection.cursor(buffered=True)
cursor.execute(update_query)
connection.commit()
context:
the variable stock is a list before I use str() on it.
userid is an int before I use str() on it.
the column stocks has a datatype of mediumtext
the column id has a datatype of text
the error I receive 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 '['gme', '1']
WHERE id = 407081272293326858' at line 2
Please help

Trying to sanitize very basic MySQL SELECT in Python/Django

This is driving my nuts. I have this very basic query that works without the sanitization statement but breaks with it. Everything I've read says to do it this way.
query = "SELECT COL1 FROM A_TABLE %s"
queryUserInput = "WHERE COL1 = 'user input value'"
cursor.execute(query, (queryUserInput,))
I receive the error:
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 '' WHERE ...
Top of the stack:
C:..\env\lib\site-packages\mysql\connector\connection_cext.py in
cmd_query
raw_as_string=raw_as_string)
Python 3.7
Django 2.1.3
Any advice is very appreciated.
Parameterisation is supposed to used to santitise a variable value which is being used to form part of the finished SQL - e.g. the 7 in a query such as SELECT * FROM user WHERE ID = 7. You can't parameterise a whole section of SQL the way you're doing - and indeed there should be no need to do so.
I don't know Python specifically, but logically I think your code should be:
query = "SELECT COL1 FROM A_TABLE WHERE COL1 = %s"
queryUserInput = "user input value"
cursor.execute(query, (queryUserInput,))
in order that it only parameterises the actual user input, and not any of the SQL.
(Your original code would produce a SQL string something like SELECT COL1 FROM A_TABLE 'WHERE COL1 = \'user input value\'' which clearly is not valid SQL at all, due to everything after A_TABLE being contained within a string literal.)
This documentation (of the execute() method) shows you some other examples of correct usage: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
you can try it:
queryUserInput = "user input value"
cursor.execute("SELECT COL1 FROM A_TABLE WHERE COL1 = %s", [queryUserInput])
and django doc:
Executing custom SQL directly

Categories