Python insert into %s MySQL - python

I am trying to insert some data into a database using the variable test as the table name. But unfortunately I cant seem to achieve this. Can anyone help me out?
From my raise I am getting:
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
My code:
test = "hello"
# Open database connection
db = MySQLdb.connect("127.0.0.1","admin","password","table" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = ("""INSERT INTO %s (name,
age, gender)
VALUES (%s, %s, %s)""",(test))
try:
# Execute the SQL command
cursor.execute(sql, (name, age, gender))
db.commit()
except:
raise
db.rollback()
# disconnect from server
db.close()

I don't think MySQLdb lets you use parameters for table names -- usually this is used for actual parameters (ones that are sometimes from user input and need sanitization - the name/age/gender part gets this right). You could use Python's string formats to achieve this:
sql = ("""INSERT INTO {table} (name, age, gender)
VALUES (%s, %s, %s)""".format(table=table), (test))

Something like this will work:
sql = """INSERT INTO %s (name, age, gender)
VALUES (%s, %s, %s)""" % (test, "%s", "%s", "%s")
You need to separate Python's string substitution from MySQL's parameter substitution. The above is a crude approach, but minimally different from your own code.

Related

Use table names as sql parameters in python [duplicate]

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

Insert data in oracle database in python

I can't insert data into database using a dynamic query in python script
def execute_query(self, qo):
query_string = "INSERT INTO " +dep_table+ " (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES (%s, %s, %s, %s, %s, %s, %s)" % ("'CO'","'"+qo.db_src+"'","'"+qo.table_src+"'","'"+qo.table_des+"'","'"+qo.check_func+"'","'"+qo.table_des+"'","'NULL'")+";"
cursor.execute(query_string)
I got this error:
ERROR: Failed to set dependencies informations : ORA-00933: SQL command not properly ended
The connection to the database is okay, but I can't insert.
Drop the semi-colon at the end of the string you are creating / executing.
It shouldn't be part of the SQL statement, rather used in some client tools to indicate the end of a statement so that the client can send it to the database to be executed.
I found the solution to the problem
connection.commit()
You can use format method in Python like below:
def execute_query(self, qo):
query_string = "INSERT INTO {0} (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7})".format(dep_table, 'CO', qo.db_src, qo.table_src, qo.table_des, qo.check_func, qo.table_des, 'NULL')
cursor.execute(query_string)

python sql escape forward slash not working

I am trying to execute an sql statement that should add some data to a database like so:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( db.escape_string(self.imdbID), self.name))
I have also tried:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( self.imdbID, self.name))
But i keep getting this error regardless of using the escape_string or not. See below:
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 '/name/nm0991810, Mahershala Ali)' at line 1")
I am pretty sure it has to do with the forward slash but i cant get it to work. How do i fix this issue?
If any more information is needed let me know!
Do this instead:
query = "INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)"
cursor.execute(query, (self.imdbID, self.name))
If I am not mistaken mysqldb takes care of this for you.
Otherwise you can do:
cursor.execute(query, (db.escape_string(self.imdbID), self.name))

PostgreSQL Schema "www" does not exist?

From the PostgreSQL documentation if you do a INSERT without specifying a schema it should be a public schema.
conn = psycopg2.connect(dbname = 'orion',
host = 'localhost',
port = 5432,
user = 'earthling',
password = 'mysupersecretpassword')
sql = conn.cursor()
def INSERT(table, info, text):
date = datetime.date.today()
query = "INSERT INTO %s (info, text, date) " \
"VALUES (%s, %s, %s)" %(table, info, text, date)
sql.execute(query)
INSERT("main", "www.capecod.edu", "test")
For some reason I'm seeing the following error?
psycopg2.ProgrammingError: schema "www" does not exist
You are using string interpolation to create the query. This is what psycopg2 executes:
INSERT INTO main (info, text, date)
VALUES (www.capecod.edu, test, 2015-09-12)
If it's not obvious what's wrong here, it's that none of the values are quoted. Here is the properly quoted version:
INSERT INTO main (info, text, date)
VALUES ('www.capecod.edu', 'test', '2015-09-12')
The error is caused by the unquoted www.capecod.edu. Due to the dots, it's being interpreted as schema.table.column.
The "right" way to do this is with a parameterized query.
query = "INSERT INTO main (info, text, date) VALUES (%s, %s, %s)"
params = (info, text, date)
sql.execute(query, params)
psycopg2 will figure out what should be quoted and how. This is a safer option than simply interpolating the string yourself, which often leaves you open to SQL injection attack.
http://initd.org/psycopg/articles/2012/10/01/prepared-statements-psycopg/
Unfortunately, you can't just toss identifiers such as the table name in as a parameter, because then they are quoted as string values, which is bad SQL syntax. I found an answer (python adds "E" to string) that points to psycopg2.extensions.AsIs as a way to pass identifiers such as table names safely as parameters. I wasn't able to make this work in my testing, though.
If you go the AsIs route, you should be cautious about checking the table names are valid, if they somehow come from user input. Something like
valid_tables = ["main", "foo", "bar", "baz"]
if table not in valid_tables:
return False

How to insert Records of data into MySQL database with python?

I have an form which has FirstName, Lastname, Age and Gender. I am using MySQL db.
While using MySQl db, do we need to create table , do the insert operation in the single pythonic script ?
For example :
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost", "usename", "password", "TESTDB")
cursor = db.cursor()
cursor.execute ( """
CREATE TABLE PERSON
(
F_NAME CHAR(20) NOT NULL,
L_NAME CHAR(20),
AGE INT,
GENDER CHAR(4)
)
""")
cursor.execute( """
INSERT INTO PERSON (F_NAME, L_NAME, AGE, GENDER)
VALUES
('Neeraj','Lad','22','Male'),
('Vivek','Pal','24','Male')
""")
print cursor.rowcount
Edited Code:
#!/usr/bin/python
import MySQLdb
import cgi
print "Content-type: text/html\n"
form = cgi.FieldStorage()
f_Name = form.getvalue('firstname', '')
l_Name = form.getvalue('lastname', '')
age = form.getvalue('age', 0)
gender = form.getvalue('gender', '')
db = MySQLdb.connect(host="", user="", password="", db="")
cursor = db.cursor()
sql = "INSERT INTO PERSON (F_NAME, L_NAME, Age, Gender) VALUES (%s, %s, %s, %s)" %(f_name, l_name, age, gender)
cursor.execute(sql)
db.commit()
db.close()
I'm not 100% clear on what you're asking, but I'll take a guess.
You have to create a table exactly once in the database before you can insert into it.
If your Python script is talking to a brand-new database each time it runs, then it needs a CREATE TABLE statement.
If your Python script might be talking to a brand-new database, but will usually be talking to an already-existing one, then you can use CREATE TABLE IF NOT EXISTS.
But, except in toy learning projects, both of these are rare. Normally, you create the database once, then you write Python scripts that connect to it and assume it's already been created. In that case, you will not have a CREATE TABLE statement in your form handler.
If you're asking about inserting multiple values in a single INSERT statement… normally, you won't be inserting hard-coded values like 'Neeraj', but rather values that you get dynamically (e.g., from the web form). So you will be using parameterized SQL statements like this:
cursor.execute("""
INSERT INTO PERSON (F_NAME, L_NAME, AGE, GENDER)
VALUES (%s, %s, %s, %s)
""", (f_name, l_name, age, gender))
In that case, if you have, say, a list of 4-tuples, each representing a person, and you want to insert all of them, you do that not by putting multiple copies of the parameter lists in the SQL statement, but by putting a single parameter list, and using the executemany function:
cursor.execute("""
INSERT INTO PERSON (F_NAME, L_NAME, AGE, GENDER)
VALUES (%s, %s, %s, %s)
""", list_of_people)
You only need to create the table once. You can do that using the mysql CLI tool, or phpmyadmin, or python/MySQLdb, or by some other method.
CREATE TABLE PERSON will raise an error if the table PERSON already exists. If you'd like a way to create it in your python script, use IF NOT EXISTS, so subsequent runs of your program do not raise an error:
cursor.execute ( """
CREATE TABLE IF NOT EXISTS PERSON
(
F_NAME CHAR(20) NOT NULL,
L_NAME CHAR(20),
AGE INT,
GENDER CHAR(4)
)
""")

Categories