简体   繁体   中英

How To pass the variable name in mysql query using python

Myquery is inserted if i give the static value in fields.but throws exception if i give the variable name. My Working code

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()

sql = "INSERT INTO selva(name) \
       VALUES ('Selva') " 
try:
   cursor.execute(sql)
   db.commit()
except: 
   print "dffds"
   db.rollback()

db.close()

My Exception Code

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()
a="surya"
sql = "INSERT INTO selva(name) \
       VALUES (%s) " %(a)
try:
   cursor.execute(sql)
   db.commit()
except: 
   print "dffds"
   db.rollback()

db.close()

It prints dfffds

How to give the variable name in query?Any help will be greatly appreciated!

Try this: Note how I am passing the variable as a param to the execute function, this is better to prevent sql injection attacks.

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()
a="surya"
b="male"
sql = "INSERT INTO selva(name, gender) VALUES (%s, %s)"
try:
   cursor.execute(sql, [a, b])
   db.commit()
except: 
   print "dffds"
   db.rollback()

db.close()

尝试

INSERT INTO table_name (name) VALUES ('selva')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM