34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
|
import sqlite3
|
|||
|
|
|||
|
if __name__ == "__main__":
|
|||
|
# 在Python中,数据库的输入和输出使用如下元组来表示
|
|||
|
stocks = [
|
|||
|
('GooG', 100, 490.1),
|
|||
|
('AAPL', 50, 545.75),
|
|||
|
('FB', 150, 7.45),
|
|||
|
('HPQ', 75, 33.2)
|
|||
|
]
|
|||
|
|
|||
|
# 首先我们需要创建一个数据库连接
|
|||
|
db = sqlite3.connect('8.db_test_sqlite3.db')
|
|||
|
print(db)
|
|||
|
|
|||
|
# 然后创建一个游标与数据库进行交互
|
|||
|
c = db.cursor()
|
|||
|
# c.execute('create table portfolio (symbol text, shares integer, price real)')
|
|||
|
# db.commit()
|
|||
|
|
|||
|
# 使用execute和executemany命令与数据库进行交互
|
|||
|
# 务必使用?作为占位符让SQL执行替换,否则这就是SQL注入攻击的漏洞
|
|||
|
c.executemany('insert into portfolio values (?, ?, ?)', stocks)
|
|||
|
db.commit()
|
|||
|
|
|||
|
for row in db.execute('select * from portfolio'):
|
|||
|
print(row)
|
|||
|
|
|||
|
c.close()
|
|||
|
db.close()
|
|||
|
|
|||
|
# 好消息是,大部分的网络框架在需要数据库时都做了ORM封装,不用这么麻烦的去写代码调动数据库了
|
|||
|
|