Printing out all the values from SQLite3 tables

时间:2018-10-02 09:08:03

标签: python printing sqlite

I want to be able to add lots of data into the table (named: Hydro_RAINFALL) then be able to print it all. At the moment I am managing to insert data into the table but when I come to print it, it only prints the first values that I INSERT into the table.

cursor.execute("SELECT * FROM Hydro_RAINFALL")
    print("\n01/08/2014:")
    res = cursor.fetchone()
    print(res)

This is the code I am using to print it all, but as I stated above, it only prints the first piece of data I INSERTed into the table.

import sqlite3

with sqlite3.connect("Weather.db") as db:
    cursor = db.cursor()

cursor.execute('''
CREATE TABLE IF NOT EXISTS Hydro_RAINFALL(
wind VARCHAR (10) NOT NULL,
temp VARCHAR (10) NOT NULL,
precipitation VARCHAR (10) NOT NULL,
humidity VARCHAR (10) NOT NULL,
date VARCHAR (20) NOT NULL);
''')
cursor.execute("""
INSERT INTO Hydro_RAINFALL(wind,temp,precipitation,humidity)
VALUES ("60mp/h", "8C", "56mm", "87%")
""")

cursor.execute("""
INSERT INTO Hydro_RAINFALL(wind,temp,precipitation,humidity)
VALUES ("39mp/h", "4C", "110mm", "45%")
""")

cursor.execute("""
INSERT INTO Hydro_RAINFALL(wind,temp,precipitation,humidity)
VALUES ("69mp/h", "6.9C", "69mm", "69%")
""")

cursor.execute("""
INSERT INTO Hydro_RAINFALL(wind,temp,precipitation,humidity)
VALUES ("456mp/h", "79C", "0mm", "99%")
""")

db.commit()




cursor.execute("SELECT * FROM Hydro_RAINFALL")
print("\n01/08/2014:")
res = cursor.fetchone()
print(res)

cursor.execute("SELECT * FROM Hydro_RAINFALL")
print("\n02/08/2014:")
res = cursor.fetchone()
print(res)

cursor.execute("SELECT * FROM Hydro_RAINFALL")
print("\n03/08/2014:")
res = cursor.fetchone()
print(res)

Thanks in advance! :)

1 个答案:

答案 0 :(得分:0)

This pagethis page指出它应该像这样工作。

请尝试

all_rows = cursor.fetchall()

for row in all_rows:

    print(row)

这将显示数据是否已正确放置在数据库中。

关于您的代码的另一条注释。您不必分别添加每一行。您可以将executemany()与占位符一起使用:

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

(来自here

另请参阅here