在Python中的For循环中添加SQL查询
在python中,如果表名和数据库名是可变的,有没有办法在For循环中添加SQL查询? 大概是这样的:在Python中的For循环中添加SQL查询,python,mysql,sql,postgresql,Python,Mysql,Sql,Postgresql,在python中,如果表名和数据库名是可变的,有没有办法在For循环中添加SQL查询? 大概是这样的: SQL = "select * from " + str(x) + "." + str(y) + " where " + str(z) + " is NOT NULL;" 数据库=[] 表=[] 列=[] 对于数据库中的x: 对于表中的y: 对于列中的z: SQL=“从x.y中选择*其中z不为空;” cursor.execute(sql)`在这里输入代码` 只需使用string对象的.for
SQL = "select * from " + str(x) + "." + str(y) + " where " + str(z) + " is NOT NULL;"
数据库=[]
表=[]
列=[]
对于数据库中的x:
对于表中的y:
对于列中的z:
SQL=“从x.y中选择*其中z不为空;”
cursor.execute(sql)`在这里输入代码`
只需使用string对象的.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;"
我推荐第一种解决方案。只需使用字符串格式。在您的示例中:
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字符串格式的一个示例,但是您可以使用字符串连接、
%formatting
或f-strings
是的,至少在理论上,这应该是可能的。您的实际问题是什么?…虽然这种问题可能是设计不良的数据库/表/列的症状,但这是可能的。例如,请查看此python sqlite文档。您使用的是MySQL还是Postgresql?两种方法都很有效,尤其是第一种,谢谢!