怎么连接sqlite数据库(如何使用Python连接SQLite数据库?)

要使用Python连接SQLite数据库,您可以使用Python标准库中的sqlite3模块。

以下是如何使用sqlite3模块连接SQLite数据库的示例代码:

import sqlite3
from sqlite3 import Error

def create_conn(database_file):
    try:
        connection = sqlite3.connect(database_file)
        print(f"成功连接到SQLite数据库,SQLite版本:{sqlite3.version}")
        return connection
    except Error as e:
        print(e)
        return None

def close_conn(connection):
    if connection:
        connection.close()
        print("数据库连接已关闭")

if __name__ == "__main__":
    database_file = "your_database_name.db"

    # 创建数据库连接
    conn = create_conn(database_file)

    if conn:
        # 在这里执行您的数据库操作(如查询、插入、更新等)

        # 关闭数据库连接
        close_conn(conn)
图片[1]-怎么连接sqlite数据库(如何使用Python连接SQLite数据库?)-不念博客

请注意将上述代码中的your_database_name.db替换为您希望连接的SQLite数据库文件名。

如果该文件不存在,sqlite3.connect()函数将创建一个新的数据库文件。

在这段代码中,您可以执行数据库操作,如查询、插入、更新等。

完成操作后,记得使用close_conn()函数关闭数据库连接。

© 版权声明
THE END
喜欢就支持一下吧
点赞75赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称

    暂无评论内容