如何使用python在mysql查询中传递变量名称

时间:2014-09-24 04:26:19

标签: php python mysql sql

如果我在fields中给出静态值,则插入Myquery。但如果我给出变量名,则抛出异常。 我的工作代码

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

我的例外代码

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

打印dfffds

如何在查询中提供变量名称?非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

试试这个: 请注意我如何将变量作为参数传递给execute函数,这样可以更好地防止sql注入攻击。

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

答案 1 :(得分:0)

尝试

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