【问题标题】:Adding SQL Queries in For Loop in Python在 Python 中的 For 循环中添加 SQL 查询
【发布时间】:2019-02-18 06:07:43
【问题描述】:

有没有办法在 python 的 For 循环中添加 SQL 查询,其中表名和数据库名是可变的? 像这样的:

database = []
tables= []
column = []

for x in database: 
    for y in tables:
        for z in column:
            SQL = "select * from x.y where z is NOT NULL;"
            cursor.execute(sql)`enter code here`

【问题讨论】:

  • 是的,这应该是可能的,至少在理论上是这样。您的实际问题是什么?
  • ...虽然这种问题可能是设计不佳的数据库/表/列的症状
  • 是的,有可能。例如,查看这个 python sqlite 文档。 docs.python.org/2/library/sqlite3.html
  • 你使用的是 MySQL 还是 Postgresql?

标签: python mysql sql postgresql


【解决方案1】:

只需使用字符串格式。在您的示例中:

database = []
tables= []
column = []

for x in database: 
    for y in tables:
        for z in column:
            SQL = "select * from {x}.{y} where {z} is NOT NULL;".format(x=x, y=y, z=z)
            cursor.execute(sql)

这是一个 Python 字符串格式化的示例,但您可以使用字符串连接,% formattingf-strings

【讨论】:

    【解决方案2】:

    只需使用字符串对象的.format()方法即可获取sql查询字符串:

    SQL = "select * from {}.{} where {} is NOT NULL;".format(x, y, z)
    

    或者像这样附加值:

    SQL = "select * from " + str(x) + "." + str(y) + " where " + str(z) + " is NOT NULL;"
    

    我推荐第一种解决方案。

    【讨论】:

    • 两种方法都很好用,尤其是第一种,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 2020-10-27
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多