MySQLdb Python写/读方法

2024-09-27 20:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾在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, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''bar'' at line 1")


Tags: thetoreaddbsqlyourbarconnection
2条回答

有个输入错误-

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

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

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

相关问题 更多 >

    热门问题