gpt4 book ai didi

python - MySQLdb Python 写/读方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:34 26 4
gpt4 key购买 nike

我在 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")

最佳答案

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

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

关于python - MySQLdb Python 写/读方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20395018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com