MySQL中的Python变量

MySQL中的Python变量,mysql,python-2.7,Mysql,Python 2.7,我想使用Python变量作为表名、列名和值,但此查询不起作用: def dodaj_do_bazy (wartosc, miejsce, tabela): # Open database connection db = MySQLdb.connect("localhost","slawomir","12345","testpy" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare

我想使用Python变量作为表名、列名和值,但此查询不起作用:

def dodaj_do_bazy (wartosc, miejsce, tabela):

# Open database connection
db = MySQLdb.connect("localhost","slawomir","12345","testpy" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
#sql = "INSERT INTO ",tabela,"(",miejsce,") VALUES(",wartosc,")"
try:
   # Execute the SQL command
   cursor.execute('INSERT INTO %s (%s) VALUES (%s)' % tabela, miejsce, (wartosc))
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()


dodaj_do_bazy(wpis_email, "email", "mail")
从我的测试中

MySQLdb希望元组作为变量,所以用括号括起来

cursor.execute('插入到%s(%s)值(%s)'(tabela、miejsce、wartosc))

这有用吗?

在此处找到,因此:

这对我来说是可行的(python 2.7.6,MariaDB)

sql=“”插入%s(%s)值(%s)”“”%(tabela、miejsce、wartosc)

并且必须引用您的插入值 wpis_email=“”无论什么“


首先,在不使用
try/except
的情况下进行尝试,因为这会吃掉任何错误消息

,所以,准备语句并打印出来。它看起来怎么样?
wpis\u电子邮件中的任何百分比字符符号(%)
?因为如果我打印这个,这些必须转义(%):print wpis_email这将返回我干净的variable而不使用try/except,因为将变量wpis_email视为列而不是值operationalError:(1054,“未知列”mail@mail.com“在“字段列表”中),当值为wpi_email=”时mail@mail.com"这在dbI中添加了三个NULL,将其更改为sql=“插入“%s”(“%s”)值(“%s”)”%tabela,miejsce,(wartosc),错误是:TypeError:没有足够的参数用于stringI使用的格式:“sql=“插入“%s”(“%s”)值(“%s”)”%(tabela,miejsce,wartosc)”并且我有错误:“ProgrammingError:(1064,”您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以了解在第1行的“mail”(“email”)值(“nom”)附近使用的正确语法。”“我看到变量没有问题,因为是语法错误