【问题标题】:MySQLdb Python write/read methods [duplicate]MySQLdb Python写/读方法[重复]
【发布时间】:2013-12-05 08:31:17
【问题描述】:

我在 Python 中使用了一些 MySQLDB,并认为我了解它的工作原理。 但现在我想定义自己的方法更灵活。阅读代码....

import MySQLdb as mydb

class DB(object):
    def read(self, slct, frm):
        connection = mydb.connect("123.12.34.56", "user", "pass", "foo")
        cursor = connection.cursor()
        cursor.execute("SELECT %s FROM %s", (slct, frm))
        print cursor.fetchall()

        connection.close()


if __name__ == '__main__':
    db = DB()
    db.read("*", "bar")

这会引发 SQL 语法错误。为什么我不能这样使用?

ProgrammingError: (1064, "您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在第 1 行的 ''bar'' 附近使用的正确语法")

【问题讨论】:

  • 打印错误会有帮助...
  • 对不起,我编辑错了。现在它是正确的。
  • 你确定foo db 中有bar 表吗?
  • 是的,我确定。 cursor.execute("SELECT * FROM bar") 工作...
  • @Tim +1!我不知道!

标签: python mysql-python


【解决方案1】:

我不太确定 mysqldb,但通常(至少在 pyodbc 和 sqlite 中)你不能参数化列或表名,只能参数化值。您可以对 * 和表名部分使用 Python 的字符串格式,并为其余部分使用参数。例如:

cursor.execute('SELECT {col} FROM {table} WHERE foo=%s'.format(col='*', table='bar'), ('my value',))

【讨论】:

    【解决方案2】:

    有错别字-

    cursor.execute("SELECT %s FROM %s"%(slct, frm))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2013-02-21
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      相关资源
      最近更新 更多