簡體   English   中英

如何使用mysaldb插入mysql表,其中表名是python變量?

[英]how to insert to a mysql table using mysaldb, where the table name is in a python variable?

我正在使用python-mysql db api將一些值插入到表名為python變量的表中。 所以我寫了下面的代碼

DB_CURSOR.execute("""INSERT INTO %s (name,created_by,state,description,docs,admin_email,date_created) VALUES(%s,%s,%s,%s,%s,%s,%s)""", (hosts_table, hostname, created_by, state, description, docroot, admin_email, date_created))

如您所見,表名在hosts_table變量中。 問題是mysqldb引用了表名,我得到了一個mysql錯誤。 當我真正使用表名時,它工作正常。 我怎么能繞過這個?

DB_CURSOR.execute("""INSERT INTO %s 
    (name,created_by,state,description,docs,admin_email,date_created) 
    VALUES(%%s,%%s,%%s,%%s,%%s,%%s,%%s)""" % hosts_table,
    (hostname, created_by, state, description, docroot, admin_email, date_created))

請注意,hosts_table變量是單個%符號,所有其他變量都是2 %%,因此在初始Python字符串插值中會忽略它們,然后將mysqldb部分更改為單個%。

在Python提示符中嘗試這個以查看我的意思:

>>> '%%s %s' % 'x'
'%s x'

嘗試類似的東西:

DB_CURSOR.execute("""INSERT INTO %s (name,created_by,state,description,docs,admin_email,date_created) VALUES(%s,%s,%s,%s,%s,%s,%s)""" % (hosts_table), (hostname, created_by, state, description, docroot, admin_email, date_created))

我不確定它會起作用但它可以:)

MySQLdb並不關心變量的名稱。 如果您對表名有hosts_table ,請嘗試將hosts_table分配給表的名稱,並查看它是否有效。

hosts_table = 'hosts_table'

或者只是print出來,看看它使用的是哪個表名:

print hosts_table

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM