搜索
首页后端开发Python教程用 Python 构建一个简单的 SQLite 库管理器

Building a Simple SQLite Library Manager in Python

用 Python 构建一个简单的 SQLite 库管理器

高效管理数据是任何项目的关键部分,而 SQLite 使这项任务变得简单而轻量。在本教程中,我们将构建一个小型 Python 应用程序来管理图书馆数据库,使您可以轻松添加和检索书籍。

读完本文,您将了解如何:

  • 创建 SQLite 数据库和表。
  • 插入记录,同时防止重复。
  • 根据特定条件检索数据。

1. 创建数据库和表

让我们首先创建 SQLite 数据库文件并定义 books 表。每本书都有标题、作者、ISBN、出版日期和流派字段。

import sqlite3
import os

def create_library_database():
    """Creates the library database if it doesn't already exist."""
    db_name = "library.db"

    if not os.path.exists(db_name):
        print(f"Creating database: {db_name}")
        conn = sqlite3.connect(db_name)
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS books (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT,
                author TEXT,
                isbn TEXT UNIQUE,
                published_date DATE,
                genre TEXT
            )
        ''')
        conn.commit()
        conn.close()
    else:
        print(f"Database already exists: {db_name}")

运行此函数来初始化数据库:

create_library_database()

这将在您的项目目录中创建一个library.db 文件,其中包含具有指定字段的书籍表。


  1. 将书籍插入数据库

要插入书籍,我们希望确保避免重复条目(基于 isbn 字段)。我们将使用 SQLite 的 INSERT OR IGNORE 语句,而不是手动检查重复项。

这是添加书籍的功能:

def insert_book(book):
    """
    Inserts a book into the database. If a book with the same ISBN already exists,
    the insertion is ignored.
    """
    conn = sqlite3.connect("library.db")
    cursor = conn.cursor()

    try:
        # Insert the book. Ignore the insertion if the ISBN already exists.
        cursor.execute('''
            INSERT OR IGNORE INTO books (title, author, isbn, published_date, genre)
            VALUES (?, ?, ?, ?, ?)
        ''', (book["title"], book["author"], book["isbn"], book["published_date"], book["genre"]))
        conn.commit()

        if cursor.rowcount == 0:
            print(f"The book with ISBN '{book['isbn']}' already exists in the database.")
        else:
            print(f"Book inserted: {book['title']} by {book['author']}")

    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        conn.close()

此函数使用 INSERT OR IGNORE SQL 语句来确保有效地跳过重复条目。


 3. 添加一些书籍

让我们通过向我们的图书馆添加一些书籍来测试 insert_book 函数。

books = [
    {
        "title": "To Kill a Mockingbird",
        "author": "Harper Lee",
        "isbn": "9780061120084",
        "published_date": "1960-07-11",
        "genre": "Fiction"
    },
    {
        "title": "1984",
        "author": "George Orwell",
        "isbn": "9780451524935",
        "published_date": "1949-06-08",
        "genre": "Dystopian"
    },
    {
        "title": "Pride and Prejudice",
        "author": "Jane Austen",
        "isbn": "9781503290563",
        "published_date": "1813-01-28",
        "genre": "Romance"
    }
]

for book in books:
    insert_book(book)

当您运行上述代码时,书籍将被添加到数据库中。如果您再次运行它,您将看到类似以下的消息:

The book with ISBN '9780061120084' already exists in the database.
The book with ISBN '9780451524935' already exists in the database.
The book with ISBN '9781503290563' already exists in the database.

4. 检索书籍

您可以通过查询数据库轻松检索数据。例如,要获取图书馆中的所有书籍:

def fetch_all_books():
    conn = sqlite3.connect("library.db")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM books")
    rows = cursor.fetchall()
    conn.close()
    return rows

books = fetch_all_books()
for book in books:
    print(book)

结论

只需几行Python,您现在就拥有了一个功能齐全的图书馆管理器,可以插入书籍,同时防止重复并轻松检索记录。 SQLite 的 INSERT OR IGNORE 是一个强大的功能,可以简化处理约束,使您的代码更加简洁和高效。

随意扩展此项目,具有以下功能:

  • 按书名或作者搜索书籍。
  • 更新图书信息。
  • 删除书籍。

接下来你会建造什么? ?

以上是用 Python 构建一个简单的 SQLite 库管理器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何将元素附加到Python数组?您如何将元素附加到Python数组?Apr 30, 2025 am 12:19 AM

Inpython,YouAppendElementStoAlistusingTheAppend()方法。1)useappend()forsingleelements:my_list.append(4).2)useextend()orextend()或= formultiplelements:my_list.extend.extend(emote_list)ormy_list = [4,5,6] .3)useInsert()forspefificpositions:my_list.insert(1,5).beaware

您如何调试与Shebang有关的问题?您如何调试与Shebang有关的问题?Apr 30, 2025 am 12:17 AM

调试shebang问题的方法包括:1.检查shebang行确保是脚本首行且无前置空格;2.验证解释器路径是否正确;3.直接调用解释器运行脚本以隔离shebang问题;4.使用strace或truss跟踪系统调用;5.检查环境变量对shebang的影响。

如何从python数组中删除元素?如何从python数组中删除元素?Apr 30, 2025 am 12:16 AM

pythonlistscanbemanipulationusesseveralmethodstoremovelements:1)theremove()MethodRemovestHefirStocCurrenceOfAstePecifiedValue.2)thepop()thepop()methodremovesandremovesandurturnturnsananelementatagivenIndex.3)

可以在Python列表中存储哪些数据类型?可以在Python列表中存储哪些数据类型?Apr 30, 2025 am 12:07 AM

pythonlistscanstoreanydatate型,包括素,弦,浮子,布尔人,其他列表和迪克尼亚式

在Python列表上可以执行哪些常见操作?在Python列表上可以执行哪些常见操作?Apr 30, 2025 am 12:01 AM

pythristssupportnumereperations:1)addingElementSwithAppend(),Extend(),andInsert()。2)emovingItemSusingRemove(),pop(),andclear(),and clear()。3)访问andmodifyingandmodifyingwithIndexingAndexingAndSlicing.4)

如何使用numpy创建多维数组?如何使用numpy创建多维数组?Apr 29, 2025 am 12:27 AM

使用NumPy创建多维数组可以通过以下步骤实现:1)使用numpy.array()函数创建数组,例如np.array([[1,2,3],[4,5,6]])创建2D数组;2)使用np.zeros(),np.ones(),np.random.random()等函数创建特定值填充的数组;3)理解数组的shape和size属性,确保子数组长度一致,避免错误;4)使用np.reshape()函数改变数组形状;5)注意内存使用,确保代码清晰高效。

说明Numpy阵列中'广播”的概念。说明Numpy阵列中'广播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增强可读性,和Boostsperformance.Shere'shore'showitworks:1)较小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能