【问题标题】:how to insert to a mysql table using mysaldb, where the table name is in a python variable?如何使用 mysaldb 插入 mysql 表,其中表名在 python 变量中?
【发布时间】:2011-08-21 15:55:18
【问题描述】:

我正在使用 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 错误。当我从字面上使用表名时,它工作正常。我该如何解决这个问题?

【问题讨论】:

    标签: python mysql-python


    【解决方案1】:

    试试这样的:

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

    我不确定它是否会起作用,但它可以:)

    【讨论】:

      【解决方案2】:

      MySQLdb 并不关心变量的名称。如果您对表名有疑问,请尝试将hosts_table 分配给您的表名,看看它是否可以工作。

      hosts_table = 'hosts_table'

      或者直接print 看看它使用的是什么表名:

      print hosts_table

      【讨论】:

      • 这不是变量命名问题。问题是 MySQLdb 对待表名变量的方式与对待列名的方式相同。因此它引用了将其视为字符串列的值。
      【解决方案3】:
      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 变量是单个 % 符号,所有其他变量都是两个 %%,因此它们在初始 Python 字符串插值中被忽略,然后更改为 mysqldb 部分的单个 %。

      在 Python 提示符下试试这个,看看我的意思:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-07
        • 2013-06-16
        • 2016-09-21
        • 2015-05-10
        相关资源
        最近更新 更多