在Python中使用SQLite数据库非常方便,Python内置了SQLite模块,无需额外安装。以下是一个简单的例子,演示如何连接到SQLite数据库、创建表格、插入数据以及查询数据。

1. 连接到SQLite数据库:

   创建一个Python脚本,连接到SQLite数据库:
   import sqlite3

   # 连接到SQLite数据库,如果不存在则会创建
   dbfile = "your_database.db"
   connection = sqlite3.connect(dbfile)

   print("Connected to the database")

   请替换 "your_database.db" 为你实际的数据库文件路径。

2. 创建表格和插入数据:

   使用 execute 方法执行SQL语句创建表格并插入数据:
   import sqlite3

   # 连接到SQLite数据库,如果不存在则会创建
   dbfile = "your_database.db"
   connection = sqlite3.connect(dbfile)

   # 创建users表格
   cursor = connection.cursor()
   cursor.execute('''
       CREATE TABLE IF NOT EXISTS users (
           id INTEGER PRIMARY KEY AUTOINCREMENT,
           username TEXT NOT NULL,
           password TEXT NOT NULL
       )
   ''')

   # 插入数据
   cursor.execute("INSERT INTO users (username, password) VALUES ('john_doe', 'password123')")

   # 提交更改
   connection.commit()

   print("Table created and data inserted")

   # 关闭数据库连接
   connection.close()

   请替换 "your_database.db" 为你实际的数据库文件路径。

3. 查询数据:

   查询数据的例子如下:
   import sqlite3

   # 连接到SQLite数据库,如果不存在则会创建
   dbfile = "your_database.db"
   connection = sqlite3.connect(dbfile)

   # 查询数据
   cursor = connection.cursor()
   cursor.execute('SELECT * FROM users')

   # 获取所有行
   rows = cursor.fetchall()

   for row in rows:
       print(f"ID: {row[0]}, Username: {row[1]}, Password: {row[2]}")

   # 关闭数据库连接
   connection.close()

   请替换 "your_database.db" 为你实际的数据库文件路径。

在 Python 中,SQLite 模块提供了很多灵活的方法来执行数据库操作。确保你有适当的权限来读写数据库文件。为了增加安全性,最好使用参数化查询,以避免 SQL 注入攻击。


转载请注明出处:http://www.zyzy.cn/article/detail/14207/SQLite