Python MySQLdb variables as table names - python

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

Related

is there a way to get the insert into to work properly in pyodbc

I can not figure out why I can not get my cursor.execute statement to work. I do not get any Python errors however the code continues to fail the try command. I am connected to SQL and I can print a list of column in the table. Here is my code.
import pyodbc
# Connect to the database
connection = pyodbc.connect(
r'DRIVER={SQL Server};'
r'SERVER=******;'
r'DATABASE=****;'
r'UID=****;'
r'PWD=*****'
)
try:
# Create a cursor
cursor = connection.cursor()
# Execute a SQL statement
cursor.execute("INSERT INTO employee table (FName, SSN) VALUES (?, ?)", "john", "123-123-1234")
connection.commit()
print("success")
except pyodbc.Error:
print("error")
connection.rollback()
# Close the cursor and connection
cursor.close()
connection.close()
I get a 42000 error when I print out the error but the syntax looks to be all correct.
cursor.execute("INSERT INTO employee table (FName, SSN) VALUES (?, ?)", "john", "123-123-1234")
I see two problems here.
First, the syntax for INSERT should look like this:
INSERT INTO tablename (column1, column2) VALUES (value1, value2)
But instead of tablename, you have employee table. If employee is the name of the table, then just use that; you don't need the extra word table hanging out there.
Second, you're passing two arguments "john", "123-123-1234" to the execute function, but this is wrong. It should be one argument, which is a list/tuple containing all the desired values, like so:
cursor.execute("...", ("john", "123-123-1234"))

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 mysql.connector module, Passing data into string VALUES %s

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

SQL insert works in Oracle SQL Developer, but not in python

I have what would appear to be a straight forward insert statement for Oracle SQL. It works properly in Oracle SQL Developer but the same command will not work in Python, complaining about
cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended.
This happens on the line for the cursor.execute() call. The query itself is:
insert into TestNamesTable (TestName, TheUser, TheProject) values ('mytest.s', 'bjurasz', 'Beta');
If run in SQL Developer I get a new row. Inside Python I get the termination error. From what I can tell its properly formed and terminated.
Here is how I construct the query in python:
sql = "insert into TestNamesTable (TestName, TheUser, TheProject) values ('%s', '%s', '%s');" % (diagname, username, project)
print sql
cursor.execute(sql)
connection.commit()
Try this:
# These are just random definitions, must be of type table requires
diagname = "DEFINE HERE"
username = "SOMEBODY"
project = "PROJECT NAME"
# Assuming you've defined your connection before
cursor.execute("""insert into TestNamesTable (TestName, TheUser, TheProject) values (:diagname, :username, :project)""",
{"diagname": diagname, #cx_Oracle likes this bind-variable looking syntax
"username": username.
"project": project})
connection.commit()

pywhois parsed results into mysql

sorry if you consider as repost, quite simple code and i suspect also a trivial error here, but can't move forward:
import whois
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="pass", db="whois")
cur = db.cursor()
wi = whois.whois("google.com")
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""") , (wi.domain_name, wi.text, wi.name_servers)
ends up in:
_mysql_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 '%s, %s, %s)' at line 1")
as said, suspecting trivial error. any suggestions? thanks a lot in advance
You placed the fetched Whois variables outside the execute function!
Change:
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""") , (wi.domain_name, wi.text, wi.name_servers)
To:
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""", (wi.domain_name, wi.text, wi.name_servers))
Edit:
And don't forget to add:
db.commit()
at the end of the script.

Categories

Resources