SQLite是一个轻量级的嵌入式数据库,它不需要独立的服务器进程或系统,非常适合于小型应用程序、移动应用和嵌入式系统。Python作为一门强大的编程语言,与SQLite的结合使用为开发者提供了极大的便...
SQLite是一个轻量级的嵌入式数据库,它不需要独立的服务器进程或系统,非常适合于小型应用程序、移动应用和嵌入式系统。Python作为一门强大的编程语言,与SQLite的结合使用为开发者提供了极大的便利。以下是掌握SQLite并轻松上手Python数据库开发的步骤:
SQLite是一个开源的关系型数据库管理系统,它具有以下特点:
在Python中,SQLite是内置的,因此无需额外安装。但是,如果你需要使用其他数据库,如MySQL或PostgreSQL,你可能需要安装相应的库。
pip install mysql-connector-pythonpip install psycopg2在Python中,你可以使用sqlite3模块连接SQLite数据库。
import sqlite3
# 连接到SQLite数据库
# 数据库文件是example.db,如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('example.db')使用cursor对象执行SQL语句来创建表。
# 创建一个表
conn.execute('CREATE TABLE IF NOT EXISTS stocks (date text, trans text, symbol text, qty real, price real)')
# 提交事务:
conn.commit()
# 关闭Cursor:
cursor.close()
# 关闭Connection:
conn.close()使用execute方法插入数据。
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('CREATE TABLE IF NOT EXISTS stocks (date text, trans text, symbol text, qty real, price real)')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# 提交事务
conn.commit()
# 关闭Cursor:
cursor.close()
# 关闭Connection:
conn.close()使用fetchall方法查询数据。
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 查询数据
cursor.execute("SELECT * FROM stocks")
# 获取查询结果
rows = cursor.fetchall()
for row in rows: print(row)
# 关闭Cursor:
cursor.close()
# 关闭Connection:
conn.close()使用execute方法更新和删除数据。
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 更新数据
cursor.execute("UPDATE stocks SET price = price * 1.1 WHERE symbol = 'RHAT'")
# 删除数据
cursor.execute("DELETE FROM stocks WHERE symbol = 'TCS'")
# 提交事务
conn.commit()
# 关闭Cursor:
cursor.close()
# 关闭Connection:
conn.close()SQLite支持事务处理,确保数据的一致性和完整性。
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 开始一个事务
conn.execute('BEGIN TRANSACTION;')
# 执行一系列操作
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
cursor.execute("UPDATE stocks SET price = price * 1.1 WHERE symbol = 'RHAT'")
# 提交事务
conn.commit()
# 关闭Cursor:
cursor.close()
# 关闭Connection:
conn.close()通过以上步骤,你可以轻松地掌握SQLite并开始使用Python进行数据库开发。记住,实践是学习的关键,尝试创建自己的数据库和应用程序,以加深对SQLite和Python数据库开发的了解。