在Python中利用内置SQLite3模块进行数据库操作的完整指南

发布时间 2024-01-10 06:53:16作者: 架构师老卢

 

在Python中,使用SQLite非常方便,Python内置了 SQLite3 模块,无需额外安装。SQLite 是一个轻量级的嵌入式数据库,适用于小型项目和单用户应用。以下是一个简单的示例,演示如何在 Python 中使用 SQLite,并提供了常见的查询、增加、修改和删除功能。

首先,确保你的 Python 安装包含 sqlite3 模块。然后,创建一个 Python 文件,例如 sqlite_example.py,并添加以下代码:

import sqlite3

def create_connection(db_file):
    """创建数据库连接"""
    try:
        connection = sqlite3.connect(db_file)
        return connection
    except sqlite3.Error as e:
        print(e)
    return None

def create_table(connection):
    """创建表"""
    try:
        cursor = connection.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS Users (
                Id INTEGER PRIMARY KEY AUTOINCREMENT,
                Name TEXT,
                Age INTEGER
            );
        ''')
        connection.commit()
        print("Table created or already exists.")
    except sqlite3.Error as e:
        print(e)

def insert_data(connection, name, age):
    """插入数据"""
    try:
        cursor = connection.cursor()
        cursor.execute("INSERT INTO Users (Name, Age) VALUES (?, ?);", (name, age))
        connection.commit()
        print("Data inserted.")
    except sqlite3.Error as e:
        print(e)

def query_data(connection):
    """查询数据"""
    try:
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM Users;")
        rows = cursor.fetchall()
        print("Id\tName\tAge")
        for row in rows:
            print(f"{row[0]}\t{row[1]}\t{row[2]}")
    except sqlite3.Error as e:
        print(e)

def update_data(connection, user_id, name, age):
    """更新数据"""
    try:
        cursor = connection.cursor()
        cursor.execute("UPDATE Users SET Name=?, Age=? WHERE Id=?;", (name, age, user_id))
        connection.commit()
        print("Data updated.")
    except sqlite3.Error as e:
        print(e)

def delete_data(connection, user_id):
    """删除数据"""
    try:
        cursor = connection.cursor()
        cursor.execute("DELETE FROM Users WHERE Id=?;", (user_id,))
        connection.commit()
        print("Data deleted.")
    except sqlite3.Error as e:
        print(e)

def main():
    # 指定数据库文件路径
    db_file = "sample.db"

    # 创建数据库连接
    connection = create_connection(db_file)

    if connection:
        # 创建表
        create_table(connection)

        # 插入数据
        insert_data(connection, "John Doe", 30)

        # 查询数据
        query_data(connection)

        # 更新数据
        update_data(connection, 1, "Updated Name", 35)

        # 查询更新后的数据
        query_data(connection)

        # 删除数据
        delete_data(connection, 1)

        # 查询删除后的数据
        query_data(connection)

        # 关闭数据库连接
        connection.close()

if __name__ == "__main__":
    main()

这个示例演示了如何使用 SQLite3 模块在 Python 中进行数据库操作。在实际应用中,你可能需要根据需求修改数据库文件路径和连接方式。这个例子创建了一个名为 Users 的表,包含 Id、Name 和 Age 字段。然后进行插入、查询、更新和删除操作。