python - 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! :)
解决方案
请试试
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)
(从这里)
另请参阅此处
推荐阅读
- java - amidi 检测到 USB midi 键盘,但 java 检测不到
- ios - 我似乎有一个弱代表的保留周期
- haskell - 您如何将列表中一对的各个元素相加?
- json - 检索 GitHub 的 JSON 文件
- php - Laravel:如何将转换后的 pdf-to-Text 文件以可读格式制作?
- java - 如何根据用户输入的首字母从数组列表中删除一系列字符串对象?
- arrays - 如何从数组中随机加权一个元素,然后根据这些权重选择它?
- ios - 如何将 MKMapItem 转换为二进制数据以存储在 Core Data 中?
- mysql - 预计增长率的价值
- json - 反序列化 Json 数组字典对