`n
在NET/" style="text-decoration: none; color: inherit;" title="Python">Python中使用SQLite数据库非常简便,主要利用`sqlite3`模块。这个模块是NET/" style="text-decoration: none; color: inherit;" title="Python">Python标准库的一部分,不需要额外安装。该模块提供了对SQLite数据库的访问能力,包括创建、查询、更新和删除数据等功能。
开启使用SQLite数据库时,首先需通过引入`sqlite3`模块来准备工作。建立连接后,可以创建数据库文件,如果文件已存在,则会连接到该文件。建立连接的基本代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonimport sqlite3conn = sqlite3.connect('example.db')```
在连接数据库后,需要创建一个游标对象,游标用于执行SQL语句。创建游标的方式为调用连接对象的`cursor()`方法,示例如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythoncursor = conn.cursor()```
接下来可以创建表格,以便数据存储。使用`CREATE TABLE` SQL命令进行表格创建。例如,下面的SQL命令用于创建一个名为`users`的表格,包含`id`、`name`和`age`这几列:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythoncursor.execute('''CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)''')```
添加数据可以用`INSERT INTO`命令。通过输入参数的方式,可以有效避免SQL注入风险。下面的代码演示如何插入一条用户数据:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythoncursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30))```
每次对数据库进行修改后,务必调用`commit()`来保存更改。若未调用该方法,数据不会写入数据库,以下是相应代码:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonconn.commit()```
查询数据可以通过`SELECT`命令实现,使用游标的`execute()`方法查询公用数据。示例代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythoncursor.execute('SELECT * FROM users')rows = cursor.fetchall()for row in rows: print(row)```
在别忘了关闭游标和连接以释放数据库资源。执行`close()`方法完成清理,代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythoncursor.close()conn.close()```
以上步骤涵盖了创建、插入、查询及关闭数据库的基本过程,SQLite在NET/" style="text-decoration: none; color: inherit;" title="Python">Python环境中十分高效,适合小型应用和学习使用。