Mysql connector Python Syntax error - python

I want to run the create function in a tkinter interface but it give me this 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 ''' (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY
KEY(id))' at line 1
This is the code. I have tried a lot of thinks but nothing...
from mysql.connector import MySQLConnection, Error
from tkinter import *
DB_HOST = 'localhost'
DB_USER = 'root'
DB_PASS = 'mysql123'
DB_NAME = 'Savings'
def create(Name):
try:
connection = MySQLConnection(host=DB_HOST,user=DB_USER,password=DB_PASS,database=DB_NAME)
cursor = connection.cursor()
tabla = Name.get()
cursor.execute("CREATE TABLE %s (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))", (tabla,))
print("Hecho!")
except Error as e:
print(e)
finally:
connection.commit()
cursor.close()
connection.close()

You cannot parameterize table or column names. Use string formatting (but make sure you trust your source or validate the input table name carefully):
cursor.execute("CREATE TABLE {table} (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))".format(table=tabla))
Note that you can use the mysql connector to escape strings:
tabla = connection.converter.escape(tabla)

Related

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.

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

Unable to INSERT with Pymysql (incremental id changes though)

When I'm using pymysql to perform operations on MySQL database, it seems that all the operations are temporary and only visible to the pymysql connection, which means I can only see the changes through cur.execute('select * from qiushi') and once I cur.close() and conn.close() and log back in using pymysql, everything seems unchanged.
However, when I'm looking at the incremental id numbers, it does increased, but I can't see the rows that were inserted from pymysql connection. It seems that they were automatically deleted?!
Some of my code is here:
import pymysql
try:
conn = pymysql.connect(host='127.0.0.1',port=3306,user='pymysql',passwd='pymysql',charset='utf8')
cur = conn.cursor()
#cur.execute('CREATE TABLE qiushi (id INT NOT NULL AUTO_INCREMENT, content_id BIGINT(10) NOT NULL, content VARCHAR(1000), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id));')
#cur.execute('DESCRIBE content')
#cur.fetchall()
cur.execute('USE qiushibaike')
for _ in range(0,len(content_ids)):
cur.execute("INSERT INTO qiushi (content,content_id) VALUES (\"%s\",%d)"%(jokes[_],int(content_ids[_])))
finally:
cur.close()
conn.close()
I solved the problem by myself...
Because the config is automatically committed, so after each SQL sentence we should commit the changes.
Approach 1:
add cur.commit() after the cur.execute()
Approach 2:
edit the connection config, add autocommit=True

Python insert variable to mysql via mysql.connector

I am trying to create one python script to insert data into mysql, but I got an error when I try to test it.
This is how I create the table:
CREATE TABLE aaa (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
data CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
This is my python script:
import mysql.connector
from time import strftime, gmtime, sleep
cnx = mysql.connector.connect(
user='root', password='abcd', database='test_db'
)
cur = cnx.cursor()
# get current timestamp
curr_time = strftime("%Y%m%d_%H%M%S", gmtime())
cur.execute(
"INSERT INTO aaa(data) VALUES (%s)", (curr_time)
)
cnx.commit()
cnx.close()
The error is like this:
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
Can anyone help me solve this problem?
replace , with % in "INSERT INTO aaa(data) VALUES (%s)", (curr_time) it should be "INSERT INTO aaa(data) VALUES (%s)"%(curr_time).
#tsh is correct use this (curr_time) -> (curr_time,) instead

Dynamic table names within MYSQL statement (Google Cloud SQL)

I am trying to drop/delete a table from within Google Cloud SQL using Python (App Engine) but I want the table name to be based on a variable, for simplicity I am using 'hello' here. For some reason it is throwing back an error at me: "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 '-IN' at line 1"
I tried the following:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS %s', (tabNameShort))
conn.commit()
I also tried:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS ' + tabNameShort)
conn.commit()
Any suggestions?
try this:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS `%s`' % tabNameShort)
conn.commit()
A warning: appending the table name directly using '+' can result in an SQL injection vulnerability, if the table name is derived, directly or indirectly, from user input.

Categories