如何在Python 3中使用sqlite3模块

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

作者选择了COVID-19救济基金来接受捐赠,这是Write for DOnations计划的一部分。

介绍 (Introduction)

SQLite is a self-contained, file-based SQL database. SQLite comes bundled with Python and can be used in any of your Python applications without having to install any additional software.

SQLite是一个独立的,基于文件SQL数据库。 SQLite与Python捆绑在一起,可在您的任何Python应用程序中使用,而无需安装任何其他软件。

In this tutorial, we’ll go through the sqlite3 module in Python 3. We’ll create a connection to a SQLite database, add a table to that database, insert data into that table, and read and modify data in that table.

在本教程中,我们将介绍Python 3中sqlite3模块 。 我们将创建一个与SQLite数据库的连接,向该数据库添加一个表,将数据插入该表,以及读取和修改该表中的数据。

For this tutorial, we’ll be working primarily with an inventory of fish that we need to modify as fish are added to or removed from a fictional aquarium.

在本教程中,我们将主要处理鱼类的清单,当将鱼类添加到虚拟水族馆或从中删除时,需要对其进行修改。

先决条件 (Prerequisites)

To get the most out of this tutorial, it is recommended to have some familiarity with programming in Python and some basic background with SQL.

为了充分利用本教程,建议您熟悉Python编程和SQL的基本知识。

You can review these tutorials for the necessary background information:

您可以查看这些教程以获取必要的背景信息:

第1步-创建与SQLite数据库的连接 (Step 1 — Creating a Connection to a SQLite Database)

When we connect to a SQLite database, we are accessing data that ultimately resides in a file on our computer. SQLite databases are fully featured SQL engines that can be used for many purposes. For now, we’ll consider a database that tracks the inventory of fish at a fictional aquarium.

当我们连接到SQLite数据库时,我们将访问最终驻留在计算机文件中的数据。 SQLite数据库是功能齐全SQL引擎,可以用于许多目的。 现在,我们将考虑一个跟踪虚构水族馆中鱼存量的数据库。

We can connect to a SQLite database using the Python sqlite3 module:

我们可以使用Python sqlite3模块连接到SQLite数据库:

import sqlite3

connection = sqlite3.connect("aquarium.db")

import sqlite3 gives our Python program access to the sqlite3 module. The sqlite3.connect() function returns a Connection object that we will use to interact with the SQLite database held in the file aquarium.db. The aquarium.db file is created automatically by sqlite3.connect() if aquarium.db does not already exist on our computer.

import sqlite3使我们的Python程序可以访问sqlite3模块。 sqlite3.connect()函数返回一个Connection对象,我们将使用该对象与文件aquarium.db保存SQLite数据库进行交互。 如果aquarium.db在我们的计算机上尚不存在,则sqlite3.connect()将自动创建aquarium.db文件。

We can verify we successfully created our connection object by running:

我们可以通过运行以下命令来验证是否成功创建了connection对象:

print(connection.total_changes)

If we run this Python code, we will see output like:

如果运行此Python代码,我们将看到类似以下的输出:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值