SQLite 数据库学习

1.install

复制代码
sudo apt update
sudo apt install sqlitebrowser

这是一个开源的图形用户界面工具,专门用于开发、管理和分析 SQLite 数据库。它支持创建或导入导出表、编辑数据、执行 SQL 查询等功能。

2.python 操作数据库

Python 内置了 sqlite3 模块,使得与 SQLite 数据库交互变得简单而直接。

  1. 创建连接
    首先,导入 sqlite3 模块并建立到数据库的连接。如果指定的数据库文件不存在,SQLite 会自动创建一个新的数据库文件。
py 复制代码
import sqlite3
# 建立连接
conn = sqlite3.connect('example.db')
# 创建游标对象
cursor = conn.cursor()
  • 创建表
py 复制代码
# 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS stocks (
    date TEXT,
    trans TEXT,
    symbol TEXT,
    qty REAL,
    price REAL
)
''')
  • 插入数据
    向表中插入数据也很简单,可以使用参数化查询来避免 SQL 注入攻击。
py 复制代码
# 单条插入
cursor.execute("INSERT INTO stocks (date, trans, symbol, qty, price) VALUES (?, ?, ?, ?, ?)",
               ('2024-12-10', 'BUY', 'RHAT', 100, 35.14))

# 批量插入
purchases = [
    ('2024-01-05', 'BUY', 'IBM', 1000, 45.0),
    ('2024-06-17', 'SELL', 'MSFT', 500, 20.0),
]
cursor.executemany("INSERT INTO stocks (date, trans, symbol, qty, price) VALUES (?, ?, ?, ?, ?)", purchases)

# 提交事务
conn.commit()
  • 查询数据: 从表中检索数据同样可以通过执行 SQL 查询实现。
py 复制代码
# 简单查询
for row in cursor.execute("SELECT * FROM stocks ORDER BY price"):
    print(row)

# 条件查询
cursor.execute("SELECT * FROM stocks WHERE symbol=?", ('RHAT',))
print(cursor.fetchall())
  • 更新和删除数据: 你也可以更新或删除记录。
py 复制代码
# 更新
cursor.execute("UPDATE stocks SET qty = ? WHERE symbol = ?", (200, 'RHAT'))
conn.commit()

# 删除
cursor.execute("DELETE FROM stocks WHERE trans = ?", ('SELL',))
conn.commit()
  • 关闭连接: 完成所有操作后,确保关闭游标和连接以释放资源。
py 复制代码
cursor.close()
conn.close()
  • 使用上下文管理器:为了简化代码并确保资源被正确清理,可以使用上下文管理器 (with 语句):
py 复制代码
with sqlite3.connect('example.db') as conn:
    with conn:  # 自动提交
        cursor = conn.cursor()
        cursor.execute("INSERT INTO stocks VALUES ('2024-12-10', 'BUY', 'AAPL', 50, 200.1)")

完整python 代码:

py 复制代码
import sqlite3

# -------- 连接数据库 --------
# 建立连接
# conn = sqlite3.connect('/mnt/data2/exp_data/1208_sql_learn/example.db')
conn = sqlite3.connect('/mnt/data2/exp_data/1208_sql_learn/example.sq3')

# 创建游标对象
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 (date, trans, symbol, qty, price) VALUES (?, ?, ?, ?, ?)",
               ('2024-12-10', 'BUY', 'RHAT', 100, 35.14))

# 批量插入
purchases = [
    ('2024-01-05', 'BUY', 'IBM', 1000, 45.0),
    ('2024-06-17', 'SELL', 'MSFT', 500, 20.0),
]
cursor.executemany("INSERT INTO stocks (date, trans, symbol, qty, price) VALUES (?, ?, ?, ?, ?)", purchases)

# 提交事务
conn.commit()

# -------- 查询数据 --------
# 简单查询
for row in cursor.execute("SELECT * FROM stocks ORDER BY price"):
    print(row)

def print_query_result(cursor, query='SELECT * FROM stocks ORDER BY price'):
    for row in cursor.execute(query):
        print(row)

# 条件查询
cursor.execute("SELECT * FROM stocks WHERE symbol=?", ('RHAT',))
print(cursor.fetchall())

# -------- 更新和删除 --------
# 更新
cursor.execute("UPDATE stocks SET qty = ? WHERE symbol = ?", (200, 'RHAT'))
conn.commit()
print_query_result(cursor)
# 删除
cursor.execute("DELETE FROM stocks WHERE trans = ?", ('SELL',))
conn.commit()
print_query_result(cursor)
# -------- 关闭连接 --------
cursor.close()
conn.close()

# # -------- 使用上下文管理器 --------
# with sqlite3.connect('example.db') as conn:
#     with conn:  # 自动提交
#         cursor = conn.cursor()
#         cursor.execute("INSERT INTO stocks VALUES ('2024-12-10', 'BUY', 'AAPL', 50, 200.1)")

3.SQL语句

python 也是调用的 sql 语句:

相关推荐
RestCloud3 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud3 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence5 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger12 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud1 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术1 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug1 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom1 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*1 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud