在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.curso

2709

被折叠的 条评论
为什么被折叠?



