Python& SQLite3从两个表中选择

时间:2014-04-30 08:47:55

标签: python sql sqlite

我已经在python中编写了这段代码,我基本上打开了我的SQLite3数据库并查看表'contact'中的每一行,然后获取每个'id'号码,然后查看表中匹配的'id' “用户”。我的问题是它只输出第一个并且不遍历所有行。

import sqlite3

conn = sqlite3.connect('sqlite3.db')

cursor = conn.cursor()
cursor2 = conn.cursor()
cursor3 = conn.cursor()

text_file = open("Output.txt", "w");
try:
    cursor.execute("SELECT Id, address FROM contact;") # Get address details by ID
    for row in cursor:
        ID = row[0]
        address= row[1]

        cursor2.execute("SELECT name FROM Users WHERE id= " + str(ID) + ";") # Get users's name by ID
        row2 = cursor2.fetchone()
        sendername = row2[0]

        text_file.write(firstname, lastname, address);


finally:
    conn.close()

任何建议,我都是python的新手。

2 个答案:

答案 0 :(得分:3)

您可以要求数据库进行连接:

cursor.execute("""\
    SELECT u.name, c.address
    FROM contact c
    INNER JOIN Users u ON u.id = c.Id
    """)
with open('Output.txt', 'w') as outfh:
    for name, address in cursor:
        outfh.write('{} {}\n'.format(name, address)

INNER JOIN告诉SQLite只选择id列上存在实际匹配的行。如果您在id表中将contact列标记为外键,则也可以使用NATURAL INNER JOIN,并省略ON子句。

答案 1 :(得分:1)

如果我理解你:

cursor.execute("SELECT Users.name, contact.address FROM Users, contact WHERE contact.Id = Users.id;")
for row in cursor:
    name= row[0]
    address= row[1]
    text_file.write(name+" "+address)