Python mysql.connector module, Passing data into string VALUES %s - python

I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this 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
If I do it like this:
sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)"),(data)
I get a tuple error..
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect (user='userDB1', password='UserPwd1',
host='somedatabase.com', database='mydatabase1')
cursor = cnx.cursor()
sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)")
data=('HelloSQLWORLD')
cursor.execute(sql_insert,data)
cnx.commit()
cnx.close()

No, don't do it the way #Jeon suggested - by using string formatting you are exposing your code to SQL injection attacks. Instead, properly parameterize the query:
query = """
INSERT INTO
Products
(title)
VALUES
(%s)"""
cursor.execute(query, ('HelloSQLWORLD', ))
Note how the query parameters are put into a tuple.

Pythonic string formatting is:
str1 = 'hello'
str2 = 'world'
'%s, %s' % (str1, str2)
Use % with tuple, not ,
For your particular case, try:
cursor.execute(sql_insert % (data))

Related

How to store a hashed password to database?

I'm using Python 3 and mysql.connector module. I could not store the hased password to the database.
Here is my code:
import bcrypt
import base64, hashlib
import mysql.connector
class test:
def __init__(self):
self.cnx = mysql.connector.connect(**Connect)
self.cursor = self.cnx.cursor()
pw = "Test123!"
password=pw.encode('utf-8')
hash_pass = bcrypt.hashpw(base64.b64encode(hashlib.sha256(password).digest()),bcrypt.gensalt())
print(hash_pass)
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
self.cnx.commit()
test()
When I run the INSERT statement, the error occurred:
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 '$2b$12$2Jo8.yam0VU5IKQxMa4EV.ReuFGeG43wmzbrFDsT5Pr5c8L2rmlP6'')' at line 1
Noted: My datatype for password is CHAR(96)
I appreciate your help.
Use query parameters instead of string-formatting.
// WRONG
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
// RIGHT
self.cursor.execute("INSERT INTO test (password) VALUE (%s)", (hash_pass,))
Both methods use %s as a placeholder, which is kind of confusing because it looks like it's doing the same thing. But the latter is not doing simple string substitution. It makes the value safe for the SQL query, either by escaping special characters, or by doing true query parameters, keeping the value separate until after the query has been parsed.

Updating SQL table using mysql python module

I am attempting to update a single value in a single cell in a SQL table using the mysql connector for python. Using the following code, I get no error messages, but nor does the table actually update. The value of the cell that I am attempting to update is sometimes empty, sometimes NULL, and sometimes contains a string. Here is my code:
query = ("UPDATE data_set SET %s = '%s' WHERE id = %s") % (column_to_change, change_to_value, row_id)
What am I doing wrong?
Edit: Thanks for the replies so far. I do not think there is any functional issue with the surrounding code (outside of the vulnerability to SQL injection, which I have fixed, here and elsewhere), as I have been effective executing similar code with different queries. Here is my code now:
column_to_change = "column2"
change_to_value = "james"
id = "1234"
cnx = mysql.connector.connect(user='user', password='password',
host='db.website.com',
database='database')
cursor = cnx.cursor()
query = ("UPDATE data_set SET %s = %s WHERE policy_key = %s")
cursor.execute(query, (column_to_change, change_to_value, id))
cursor.close()
cnx.close()
If it's relevant, it turns out the cells I'm trying to insert into are formatted as VARCHAR(45). When I run a SELECT query on a cell, it returns a name formatted like: (u'James',)
If I set change_to_value = "(u'James',)", I receive the following error message:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntac; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''column1' = '(u\'James\',)' WHERE id = '1234'' at line 1
Make sure you are following all the steps:
conn = pyodbc.connect("SERVER=my.server;DATABASE=my_database;UID=my_user;PWD=my_password;",ansi=True)
cursor = conn.cursor()
query = ("UPDATE data_set SET %s = '%s' WHERE id = %s") % (column_to_change, change_to_value, row_id)
cursor.execute(query)
And also verify the SQL query that your passing to .execute() is same as that you want to run on your database
Depending on your version of Python, perhaps it is an issue with your string interpolation. Otherwise, you may not be connecting your cursor and executing the query successfully. I am assuming you are executing your query elsewhere in your code, but in the instance you are not, this should work:
cursor.execute ("""
UPDATE data_set
SET %s=%s
WHERE id=%s
""", (column_to_change, change_to_value, row_id))
Alternatively, you could store this query in a variable as you have done, assign the respective variables and execute afterward like so:
query = (“UPDATE data_set SET %s=%s WHERE id=%s”)
column_to_change = [YOUR ASSIGNMENT HERE]
change_to_value = [YOUR ASSIGNMENT HERE--if this is a string, it should be formatted as such here]
row_id = [YOUR ASSIGNMENT HERE]
cursor.execute(query, (column_to_change, change_to_value, row_id))
Basic string interpolation is prone to SQL injection and should be avoided.
For more reference, see here

Python MySQLdb variables as table names

I have a syntax error in my python which which stops MySQLdb from inserting into my database. The SQL insert is below.
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
I get the following error in my stack trace.
_mysql_exceptions.ProgrammingError: (1064, "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 ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
I would really appreciate assistance as I cannot figure this out.
EDIT:
Fixed it with the following line:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Not the most sophisticated, but I hope to use it as a jumping off point.
It looks like this is your SQL statement:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC, the name of the table is not able to be parameterized (because it gets quoted improperly). You'll need to inject that into the string some other way (preferably safely -- by checking that the table name requested matches a whitelisted set of table names)... e.g.:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))

How to intsert quotation mark `'` into mariaDB using mysql-client?

I am using mariaDB(Ver 15.1 Distrib 10.0.17-MariaDB, for osx10.10 (x86_64)) and mysqlclient==1.3.6.
I just want to insert a string into a varcharfield.
import MySQLdb
import json
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='ng')
cur = conn.cursor()
cur.execute(INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, '{name}');".format(name="Lily' dog"))
conn.commit()
but I always got a error like this:
_mysql_exceptions.ProgrammingError: (1064, "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 dog', NULL)' at line 1")
what should I do if I want to insert quotation mark by mysql-client?
According to Amadan's comment, in bobby-tables(the site for preventing SQL injections), it suggest:
Using the Python DB API, don't do this:
Do NOT do it this way:
cmd = "update people set name='%s' where id='%s'" % (name, id)
curs.execute(cmd)
Instead, do this:
cmd = "update people set name=%s where id=%s"
curs.execute(cmd, (name, id))
so in my situation, just modify the execute line to :
cmd = "INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, %s);"
cur.execute(cmd, ("Lily's dog"))
and this can avoid the error which quotation mark leads to.

SQL query using %s in Python 3.3

I'm trying to retrieve data from a MySQL-database.
A = "James"
query = ("SELECT * FROM DB.tblusers WHERE UserName = %s ")
c = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='DB')
cur1 = c.cursor()
cur1.execute(query, A)
Gives the following error message:
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 '%' at line 1
But the SQL works in the mySQL Workbench.
Any ideas?
A should be a tuple, try with A = ("James",)
see documentation of MySQLCursor.execute(operation, params=None, multi=False)
EDIT: added a comma, thanks to "swordofpain" (I learned something)

Categories

Resources