简体   繁体   English

Python和SQLite3从两个表中选择

[英]Python & SQLite3 Selecting from two tables

I have written this code in python, which I basically opens up my SQLite3 database and looks at each row in the table 'contact' and then takes each 'id' number and then looks at the matching 'id' in the table 'Users'. 我已经用python编写了这段代码,基本上我打开了SQLite3数据库,查看了表“ contact”中的每一行,然后获取了每个“ id”号,然后查看了“ Users”表中的匹配“ id” 。 My problem is that it only outputs the first one and does not loop through all the rows. 我的问题是,它仅输出第一个,而不循环遍历所有行。

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()

Any suggestions, I'm very new to python. 任何建议,我对python都是新手。

You can ask the database to do a join instead: 您可以要求数据库进行联接:

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)

The INNER JOIN tells SQLite to only pick rows for which there is an actual match on the id columns. INNER JOIN告诉SQLite只选择id列上实际匹配的行。 If you marked the id column as a foreign key in the contact table, you could use a NATURAL INNER JOIN as well, and omit the ON clause. 如果在contact表中将id列标记为外键,则也可以使用NATURAL INNER JOIN ,并省略ON子句。

If I understand you: 如果我了解您:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM