首页 > 解决方案 > Printing out all the values from SQLite3 tables

问题描述

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! :)

标签: pythonprintingsqlite

解决方案


这个页面这个页面状态它应该像那样工作。

请试试

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)

(从这里

另请参阅此处


推荐阅读