如何使用Python3操作SQLite嵌入式数据库?
发表时间: 2023-08-13 14:39
#暑期创作大赛#
SQLite在Python上的应用非常广泛,它是一个轻量级的嵌入式数据库引擎,适用于小型项目和临时数据存储。下面是一些SQLite在Python上的常见应用:
SQLite在Python中的应用非常灵活,可以根据项目需求进行定制和扩展。通过Python的sqlite3模块,您可以方便地连接、操作和管理SQLite数据库。
当使用Python 3操作SQLite时,以下是25个常见的代码示例,每个示例都有详细的注释:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
cursor.execute("INSERT INTO students (name, age) VALUES ('John', 20)")
conn.commit()
cursor.execute("SELECT * FROM students")rows = cursor.fetchall()for row in rows: print(row)
cursor.execute("SELECT * FROM students WHERE age > 18")
cursor.execute("UPDATE students SET age = 21 WHERE name = 'John'")
cursor.execute("DELETE FROM students WHERE name = 'John'")
cursor.execute("PRAGMA table_info(students)")columns = cursor.fetchall()for column in columns: print(column[1])
name = 'Alice'age = 22cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", (name, age))
age = 20cursor.execute("SELECT * FROM students WHERE age > ?", (age,))
with conn: conn.execute("UPDATE students SET age = 23 WHERE name = 'Alice'")
conn.rollback()
with open('script.sql', 'r') as file: sql_script = file.read()cursor.executescript(sql_script)
last_row_id = cursor.lastrowid
with sqlite3.connect('database.db') as conn: cursor = conn.cursor() # 执行数据库操作
sql_query = "INSERT INTO students (name) VALUES (?);"data = [('Bob',), ('Carol',), ('Dave',)]cursor.executemany(sql_query, data)
data = [('Bob', 21), ('Carol', 22), ('Dave', 23)]with conn: conn.executemany("INSERT INTO students (name, age) VALUES (?, ?)", data)
cursor.execute("SELECT * FROM students ORDER BY age DESC")Python
cursor.execute("SELECT * FROM students LIMIT 10")
cursor.execute("SELECT * FROM students LIMIT 10 OFFSET 20")
cursor.execute("SELECT students.name, grades.grade FROM students JOIN grades ON students.id = grades.student_id")
cursor.close()conn.close()