PyMySQL - Using a string as cursor.execute argument [duplicate] - python

This question already has answers here:
Executing raw SQL against SQLite with Django results in `DatabaseError: near "?": syntax error`
(2 answers)
Variable table name in sqlite
(9 answers)
Closed 4 years ago.
My problem here involves passing a string inside cursor.execute below
import pymsyql
import json
connection = pymysql.connect(
host='localhost', user='u_u_u_u_u',
password='passwd', db='test',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
)
def get_data(table):
try:
with connection.cursor() as cursor:
sql = """
SELECT * FROM %s;
"""
cursor.execute(sql, (table,))
result = cursor.fetchall()
return json.dumps([dict(ix) for ix in result])
except (TypeError, pymysql.err.ProgrammingError) as error:
print(error)
finally:
pass
get_data('table_1')
connection.close()
I get the error
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 ''table_1'' at line 1")
It seems that execute does not want a string passed as an argument; when I enter a string directly, like cursor.execute(sql, ('table_1',)), I get the same error.
I'm puzzled as to what is causing the issue, the dual-quotes ''table_1'' are confusing. Can anyone tell me what's going on here?

You cannot pass a table name as a parameter, alas. You have to munge it into the query string:
sql = """
SELECT * FROM `{0}`;
""".format(table)
cursor.execute(sql)

Related

Passing string variable to the Postgres LIKE query [duplicate]

This question already has answers here:
how to safely generate a SQL LIKE statement using python db-api
(3 answers)
Closed yesterday.
In my flask app I am trying to pass a string to the query below:
tag = "Abcd"
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT * FROM database WHERE message LIKE %s ESCAPE ''", (tag,))
data = cur.fetchall()
cur.close()
conn.close()
I receive blank result.
I use psycopg2. My Postgres database has message containing "Abcd" and it works fine if I simply do:
cur.execute("SELECT * FROM database WHERE message LIKE '%Abcd%'")
If I try to pass it as a variable "tag" is my syntax for LIKE query correct?
you need to add % in your tag.
Try this:
tag = '%Abcd%' #--->> change here, add %Abcd%
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT * FROM database WHERE message LIKE %s ESCAPE ''", (tag,))
data = cur.fetchall()
cur.close()
conn.close()

how to insert string into query in python pymysql

I have a following query:
cursor = connection.cursor()
query = """
SELECT *
FROM `my_database`.table_a
"""
result = cursor.execute(query)
which works as expected. But I need to change my_database in cursor.execute. I try:
cursor = connection.cursor()
query = """
SELECT *
FROM %s.table_a
"""
result = cursor.execute(query, ("my_database",))
which gives an error 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 ''my_database'.table_a at line 2")
how can I insert database name in cursor.execute please?
It is not possible to bind a database name (or any other database object name) using a placeholder in a prepared statement. This would be, among other problems, a security risk. However, you might be able to use an f-string here instead:
cursor = connection.cursor()
db_name = "my_database"
query = f"""
SELECT *
FROM {db_name}.table_a
"""
result = cursor.execute(query)
It should also be mentioned that the above is only SQL injection safe if you are certain that the database name is not coming from outside your own application.

MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versi [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 1 year ago.
I am trying to insert data into a MySQL table using my Flask app as shown below;
#Create MySQL connection and write data into the table user_data from the POST form
sql_cursor = mysql.connection.cursor()
sql_cursor.execute("""INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value)
VALUES (new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],
add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_value);""")
mysql.connection.commit()
sql_cursor.close()
This does not work too:
sql_cursor = mysql.connection.cursor()
sql_cursor.execute("INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_value))
mysql.connection.commit()
sql_cursor.close()
I get the below error:
I get the below error:
MySQLdb._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 'condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value)\n ' at line 1")
Someone please help me.
The homepage explains how to use placeholders https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
If your variables are all valid.
this should work
sql_cursor.execute("""INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value)"""\
""" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, %s);""",(new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],
add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_valu)))
mysql.connection.commit()
sql_cursor.close()
Apparently, your connection driver is not configured to accept line breaks \n, try change your template string using concatenation or all inline statement...
sql_cursor = mysql.connection.cursor()
sql_cursor.execute("""INSERT INTO user_data (make,model,trim,fuel_type,transmission,condition,body_type,region,descriptn,eng_capacity,year,mileage, estm_value) VALUES (new_info['make'],new_info['model'],new_info['trim'],new_info['fuel_type'],new_info['transmission'],new_info['condition'],add_bodytype['body_type'],add_region['region'],new_data['description'],new_data['eng_capacity'],year,new_data['mileage'], estm_value);""")
mysql.connection.commit()
sql_cursor.close()

Python MySQL, get special column names

I am using Python to fetch MySQL process.
The codes are shown below:
import mysql.connector
mydb = mysql.connector.connect(
host='192.168.95.9', user='root',
passwd='qwe123', database='information_schema')
cursor = mydb.cursor()
sql = "SELECT CONCAT('KILL ',id,';') FROM information_schema.processlist
WHERE `TIME`>100 AND `COMMAND` = 'Sleep' AND `DB` IN ('api','monitor', 'workflow');"
cursor.execute(sql)
cursor.fetchall()
The sql shown above can get results but in python, it returns nothing. When I get rid of the where condition, it returns values as expected. I also tried
sql = "SELECT CONCAT('KILL ',id,';') FROM information_schema.processlist WHERE \`TIME\`>100 AND \`COMMAND\` = 'Sleep' AND \`DB\` IN ('api','monitor', 'workflow');"
But it returns 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 '\`TIME\`>100 lim
How to address this issue?

How to create a database with psycopg2 using execute() second argument?

I'm trying to create a database with the name a user will provide. As far as I know the correct way is to use the second argument of execute().
So I did as follows:
import psycopg2
conn = psycopg2.connect(host="...", dbname="...",
user="...", password="...", port='...')
cursor = conn.cursor()
query = ''' CREATE DATABASE %s ;'''
name = 'stackoverflow_example_db'
conn.autocommit = True
cursor.execute(query, (name,))
cursor.close()
conn.close()
And I got this error:
psycopg2.errors.SyntaxError: syntax error at or near "'stackoverflow_example_db'"
LINE 1: CREATE DATABASE 'stackoverflow_example_db' ;
I need to do this statement avoiding SQL injection, so using the second argument is a must.
You can't pass values as second argument of execute(), if the statement is a CREATE DATABASE one.
As pointed out by unutbu one way to approach this is using the psycopg2.sql submodule and use identifiers to build the statement avoiding SQL injection.
The code:
import psycopg2
from psycopg2 import sql
conn = psycopg2.connect(host="...", dbname="...",
user="...", password="...", port='...')
cursor = conn.cursor()
query = ''' CREATE DATABASE {} ;'''
name = 'stackoverflow_example_db'
conn.autocommit = True
cursor.execute(sql.SQL(query).format(
sql.Identifier(name)))
cursor.close()
conn.close()
Other aditional observations:
format() do not work with %s, use {} instead
Autocommit mode is a must for this statement to work
The specified connection user needs creation privileges

Categories