Python MYSQLdb how to execute insert with different parameters -


how can perform mysqldb inserts different parameters? example says:

add_employee = ("insert employees "                "(first_name, last_name, hire_date, gender, birth_date) "                "values (%s, %s, %s, %s, %s)")  data_employee = ('geert', 'vanderkelen', tomorrow, 'm', date(1977, 6, 14))  cursor.execute(add_employee, data_employee) 

what want is

cursor.execute("insert %s (%s) values (%s)", ('animals', 'name', 'fox')) 

but an error

mysql error [1064]: have error in sql syntax; check manual corresponds mysql server version right syntax use near ''animals' ('name') values ('fox')' @ line 1 

i understand formatter of mysqldb working wrong, there way fix that? and, somehow possible such thing

cursor.execute("insert %s (%s) values (%s)", ('animals', ('name','color'), ('fox', 'orange')) 

edit: please don't base answer on assumption inserted data strings. want able pass blob data these queries

imageofafox = open('fox.jpg', 'rb').read() sql = "insert %s (%s) values (%s)" cursor.execute(sql, ('animals', 'name, picture', ('fox', imageofafox))) 

cursor.execute auto-quote given parameters, query not have been working, because table name , field names quoted :)

only if use pythons build-in % instead of , should wrap values in ' make sure:

cursor.execute("insert %s (%s) values (%s)" % ('animals', 'name', "'fox'")) 

and if want include multiple fields , values remember passing them 3 strings (also numbers , other values auto-quoted mysql handle data typing):

cursor.execute("insert %s (%s) values (%s)" % ('animals', 'name, color', "'fox', 'orange'")) 

you can test outcome print , %

print "insert %s (%s) values (%s)" % ('animals', 'name, color', "'fox', 'orange'") 

as far know though, can not pass arrays single parameter execute, list of parameters, ('animals', ['name', 'color'], ... not work!

here complete script testing , figuring out why won't work in environment, because sure in mine:

import mysql.connector  connection = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='test') cursor = connection.cursor() sql = "insert %s (%s) values (%s)" arg = ('animals', 'name', "'fox'")  cursor.execute('set profiling = 1') try:     cursor.execute(sql % arg)     connection.commit() except:     cursor.execute('show profiles')     row in cursor:         print(row)     raise  connection.close() 

explanation: if use cursor.execute(sql, args) function auto quote values. since sql contains not %s values table name , field names, can not let them auto quoted, otherwise sql fail. if use cursor.execute(sql % args) have add quotes values query won't fail because table name , field name not quoted.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -