2025-09-10:仓库迁移
This commit is contained in:
33
6.数据编码与处理/8.同关系型数据库进行交互.py
Normal file
33
6.数据编码与处理/8.同关系型数据库进行交互.py
Normal file
@@ -0,0 +1,33 @@
|
||||
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封装,不用这么麻烦的去写代码调动数据库了
|
||||
|
Reference in New Issue
Block a user