当变量具有特殊字符时,如何在sql语句中使用变量

3pmvbmvn  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(383)

我试图在for循环中从几个不同的表中选择数据列,每个表名都以数字开头,标题为0\u training\u market到155\u training\u market。要在sql语句中使用以数字开头的表,我必须在标题周围使用一对额外的引号,这只会将变量转换为字符串,而不会读取实际的变量。这是我的代码和错误:

for j in list(range(156)):
    generation = str(j)+'_training_market'
    energy_source = db.query(" SELECT energy_source FROM " + generation + " WHERE id < 100 ORDER BY id ")
    quantity = db.query(" SELECT quantity FROM " + generation + " WHERE id < 100 ORDER BY id ")

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "0"
LINE 1:  SELECT energy_source FROM 0_training_market WHERE id < 100 ...
                                   ^

[SQL:  SELECT energy_source FROM 0_training_market WHERE id < 100 ORDER BY id ]

我不知道如何解决这个问题,所以任何帮助都是感激的。谢谢

zqdjd7g9

zqdjd7g91#

postgresql需要在名称不正确的对象周围使用双引号:

for j in list(range(156)):
    generation = str(j)+'_training_market'
    energy_source = db.query(""" SELECT energy_source FROM "{}" WHERE id < 100 ORDER BY id """.format(generation))
    quantity = db.query(""" SELECT quantity FROM "{}" WHERE id < 100 ORDER BY id """.format(generation))

相关问题