【问题标题】:python StringBuilder for MySQL query execution用于 MySQL 查询执行的 python StringBuilder
【发布时间】:2013-07-22 02:17:45
【问题描述】:

我正在尝试查询我的数据库,其中一列是 python 变量:

weekNum = "week" + str(i)               #i is either 2, 3, 4, 5
cur.execute("select %s from golden_table where nGram = %s and hash_tag = %s", (weekNum, tup[0], tup[1]))

请注意,SQL 表:golden_table 包括 4 列:week2 week3 week4 week5。 但是,python 或 MySQL 不会将 weekNum 的值视为一列。相反,查询返回的是值“weeki”。我在哪里如上。在 Java 中,我知道解决这个问题的方法是 StringBuilder 类。

  1. 在python中解决这个问题的等效方法是什么?
  2. 在 python 中解决这个问题的更好方法是什么?

感谢所有帮助,如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: python mysql query-string stringbuilder


    【解决方案1】:

    如果您的 python 版本是最新的(2.6+)。你可以使用格式。

    weekNum = "week" + str(i)               #i is either 2, 3, 4, 5
    query = "select {0} from golden_table where nGram = %s and hash_tag = %s".format(weekNum)
    cur.execute(query, (tup[0], tup[1]))
    

    【讨论】:

      【解决方案2】:

      execute 中的参数替换用于值,而不是字段名。您需要为此使用正常的字符串插值。所以:

      sql = "select %s from golden_table where nGram = %%s and hash_tag = %%s" % weekNum
      cur.execute(sql, tup)
      

      注意第一个语句中的双百分号,以便它们毫发无损地通过字符串插值。

      【讨论】:

        猜你喜欢
        • 2018-06-01
        • 1970-01-01
        • 2011-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-13
        • 2013-06-30
        • 1970-01-01
        相关资源
        最近更新 更多