从Python执行不同where子句的SQL

时间:2017-04-09 01:08:34

标签: python mysql

我试图通过python代码打印SQL结果,我试图从for循环传递where子句的不同谓词。但是代码只从循环中取出最后一个值并给出结果。

在下面的例子中,我有两个不同的id值' aaa'和' bbb'。 id值=' aaa'有4条记录。和2个记录的id值=' bbb'。 但是下面的代码只给出了id值的结果=' bbb'不是为了身份价值' aaa'

任何人都可以帮助确定我在做什么吗?

Enter name of the classlist file: classlist.txt
Completed reading of file classlist.txt
N00000001: John, john@amail.com
, marks: []
N00000002: Kelly, kelly@bmail.com
, marks: []
N00000003: Nicky, nicky@cmail.com
, marks: []
N00000004: Sam, sam@dmail.com
, marks: []
N00000005: Adam, adam@amail.com, marks: []

我得到的结果如下

import pymysql

db = pymysql.connect(host="localhost", user="user1", passwd="pass1", db="db1")

cur = db.cursor()

in_lst=['aaa', 'bbb']

for i in in_lst:
    Sql = "SELECT id, val, typ FROM test123 Where id='{inpt}'".format(inpt=i)

print(Sql)
cur.execute(Sql)

records = cur.fetchall()
print(records)

db.close()

2 个答案:

答案 0 :(得分:0)

for循环中,您要格式化sql语句以替换" {inpt}"与" aaa"。但是,在您使用该值执行任何操作之前,请立即使用" bbb"覆盖它。版。

你需要:

  1. 在循环的下一次迭代之前以某种方式存储结果,然后在循环之外处理它们。
  2. 在循环中处理结果。
  3. 以下内容将为您提供一个包含fetchall()调用结果的列表:

    import pymysql
    
    db = pymysql.connect(host="localhost", user="user1", passwd="pass1", db="db1")
    
    cur = db.cursor()
    
    in_lst=['aaa', 'bbb']
    records = list()
    for i in in_lst:
        Sql = "SELECT id, val, typ FROM test123 Where id='{inpt}'".format(inpt=i)
    
        print(Sql)
        cur.execute(Sql)
    
        records.append(cur.fetchall())
    print(records)
    
    db.close()
    

答案 1 :(得分:0)

@angular/http

缩进是您的问题,请根据您的需要更新代码......

相关问题