我试图从我的数据库中提取数据,并将其以一种格式显示在chart.js中。我使用python,我的数据库使用sqlite3。我设法从表中提取必要的值,并以表格格式打印出来,但我不知道从哪里开始。
from os import mkdir
import sqlite3
try:
conn = sqlite3.connect('foldername/db.sqlite')
except sqlite3.OperationalError:
mkdir('foldername')
finally:
conn = sqlite3.connect('foldername/db.sqlite')
cursor = conn.cursor()
room_no = 1
cursor.execute(
"SELECT room, strftime( '%H:00', date ) AS HOUR, SUM(count) AS DENSITY FROM crowd WHERE strftime('%Y-%m-%d', date) = strftime('%Y-%m-%d','now') AND room = ? group by HOUR order by HOUR asc",(room_no,))
for row in cursor:
print('{0} : {1}, {2}'.format(row[0], row[1], row[2]))
cursor.close()
conn.close()
澄清一下,目前的输出是这样打印的。
1 : 09:00, 3
1 : 10:00, 4
1 : 11:00, -2
1 : 12:00, 1
1 : 13:00, 1
1 : 14:00, 1
但我需要把不同的列变成这样的数组。
['09:00','10:00','11:00',...]
[3, 4, -2,...]
有什么建议吗?
你可以使用 zip(*...)
在python中 transpose
你的数据。
cursor.execute("SELECT room, strftime( '%H:00', date ) AS HOUR, SUM(count) AS DENSITY FROM crowd WHERE strftime('%Y-%m-%d', date) = strftime('%Y-%m-%d','now') AND room = ? group by HOUR order by HOUR asc",(room_no,))
data = cursor.fetchall()
data = list(zip(*data))
data[1]
将会 ['09:00','10:00','11:00',...]
((data[0])
是房间)