来自变量的Pymysql表名

时间:2017-09-06 18:04:08

标签: python mysql python-3.x pymysql

我正在使用Python3和PyMySQL 0.7.9。 Mysql的版本是5.5.57

使用此查询从Mysql中获取数据:

cur.execute('SELECT date FROM Tablename1 ORDER BY id DESC LIMIT 1')

我想从变量中获取表的名称。 阅读Pymysql文档和this Stackoverflow帖子让我相信这段代码应该有效:

dbtable = Tablename1
query = 'SELECT date FROM %s ORDER BY id DESC LIMIT 1'
cur.execute(query, (dbtable, ))

但这会导致错误:

pymysql.err.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 ''Tablename1' ORDER BY id DESC LIMIT 1' at line 1")

我也尝试过使用引号但出现了不同的错误:

query = 'SELECT `date` FROM `%s` ORDER BY `id` DESC LIMIT 1'
cur.execute(query, (dbtable, ))

结果:

pymysql.err.ProgrammingError: (1146, "Table 'Databasename.'Tablename1'' doesn't exist")

如何更改查询以允许变量工作?

2 个答案:

答案 0 :(得分:1)

这对我有用。使用 python 3.8、mariadb 10.2、pymysql

cur = con.cursor()
cur.execute('SELECT field FROM %s ORDER BY id DESC LIMIT 1' %(dbtable))
result = cur.fetchone()

适当地替换字段和数据库表

答案 1 :(得分:0)

像这样:

dbtable = input("Table name: ")
query = "SELECT * FROM %s"%(dbtable)
cur.execute(query)

results = cur.fetchall()

for row in results:
print (row[0], row[1], row[2], row[3])