如何使用Python和sqlite3构建一个轻量级的数据采集和分析平台
import sqlite3
# 连接到SQLite数据库(如果不存在则创建)
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)
''')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2020-01-05', 'BUY', 'RHAT', 100, 35.14)")
# 查询数据
cursor.execute('SELECT * FROM stocks ORDER BY price, qty')
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.commit()
conn.close()
这段代码演示了如何使用Python的sqlite3库来连接到一个SQLite数据库,创建一个简单的表,插入一些数据,并对数据进行查询。这个过程展示了如何在实际应用中使用SQLite作为轻量级数据存储和管理的解决方案。
评论已关闭