Files
Python_CookBook_repo/6.数据编码与处理/8.同关系型数据库进行交互.py
2025-09-10 16:12:45 +08:00

34 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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封装不用这么麻烦的去写代码调动数据库了