sqlite是一种轻量级的嵌入式数据库,广泛应用于各种应用程序中。
python提供了内置的sqlite3模块,使得连接和操作sqlite数据库变得非常简单。
下面我将详细介绍如何使用sqlite3模块来连接sqlite数据库,并提供一些实际开发中的建议和注意事项。
1. 使用 sqlite3 连接sqlite数据库
sqlite3 是python标准库中的一个模块,无需额外安装即可使用。
连接数据库
下面是一个简单的示例,展示如何连接到sqlite数据库:
import sqlite3 # 创建数据库连接 conn = sqlite3.connect('example.db') # 创建游标对象 cur = conn.cursor() # 创建表 cur.execute('''create table if not exists users ( id integer primary key, name text not null, email text not null)''') # 插入数据 cur.execute("insert into users (name, email) values (?, ?)", ('alice', 'alice@example.com')) cur.execute("insert into users (name, email) values (?, ?)", ('bob', 'bob@example.com')) # 提交事务 conn.commit() # 查询数据 cur.execute("select * from users") rows = cur.fetchall() for row in rows: print(row) # 关闭游标和连接 cur.close() conn.close()
注意事项
- 错误处理:在实际开发中,应该添加错误处理机制,以防止数据库操作失败或其他异常情况。
import sqlite3 try: conn = sqlite3.connect('example.db') cur = conn.cursor() cur.execute('''create table if not exists users ( id integer primary key, name text not null, email text not null)''') cur.execute("insert into users (name, email) values (?, ?)", ('alice', 'alice@example.com')) cur.execute("insert into users (name, email) values (?, ?)", ('bob', 'bob@example.com')) conn.commit() cur.execute("select * from users") rows = cur.fetchall() for row in rows: print(row) except sqlite3.error as e: print(f"error: {e}") finally: if cur: cur.close() if conn: conn.close()
- 上下文管理器:为了确保资源被正确释放,可以使用上下文管理器(
with
语句)来管理数据库连接和游标。
import sqlite3 try: with sqlite3.connect('example.db') as conn: with conn.cursor() as cur: cur.execute('''create table if not exists users ( id integer primary key, name text not null, email text not null)''') cur.execute("insert into users (name, email) values (?, ?)", ('alice', 'alice@example.com')) cur.execute("insert into users (name, email) values (?, ?)", ('bob', 'bob@example.com')) conn.commit() cur.execute("select * from users") rows = cur.fetchall() for row in rows: print(row) except sqlite3.error as e: print(f"error: {e}")
2. 使用参数化查询
为了避免sql注入攻击,应该使用参数化查询。
import sqlite3 try: with sqlite3.connect('example.db') as conn: with conn.cursor() as cur: cur.execute('''create table if not exists users ( id integer primary key, name text not null, email text not null)''') cur.execute("insert into users (name, email) values (?, ?)", ('alice', 'alice@example.com')) cur.execute("insert into users (name, email) values (?, ?)", ('bob', 'bob@example.com')) conn.commit() cur.execute("select * from users where name = ?", ('alice',)) rows = cur.fetchall() for row in rows: print(row) except sqlite3.error as e: print(f"error: {e}")
3. 使用事务
sqlite支持事务操作,可以通过事务来确保数据的一致性和完整性。
import sqlite3 try: with sqlite3.connect('example.db') as conn: with conn.cursor() as cur: cur.execute('''create table if not exists users ( id integer primary key, name text not null, email text not null)''') conn.execute("begin transaction") try: cur.execute("insert into users (name, email) values (?, ?)", ('alice', 'alice@example.com')) cur.execute("insert into users (name, email) values (?, ?)", ('bob', 'bob@example.com')) conn.commit() except sqlite3.error as e: conn.rollback() print(f"error: {e}") cur.execute("select * from users") rows = cur.fetchall() for row in rows: print(row) except sqlite3.error as e: print(f"error: {e}")
实际开发中的建议
- 错误处理:始终添加错误处理机制,以确保在数据库操作失败时能够捕获并处理异常。
- 资源管理:使用上下文管理器来管理数据库连接和游标,确保资源被正确释放。
- 参数化查询:使用参数化查询来防止sql注入攻击,确保数据库操作的安全性。
- 事务管理:合理使用事务来确保数据的一致性和完整性。
- 日志记录:在生产环境中,添加日志记录机制,以便在出现问题时能够追踪和调试。
在python中连接sqlite数据库,sqlite3
模块提供了一个简单且强大的接口。通过合理使用上下文管理器、参数化查询和事务管理,可以提高代码的健壮性和性能,确保数据库操作的安全性和可靠性。在实际开发中,应该注意错误处理、资源管理和日志记录,以确保系统的稳定性和可维护性。
通过这些方法和技巧,你可以有效地连接和管理sqlite数据库,满足各种复杂的需求。
拓展:python操作sqlite数据库
创建sqlite数据库
在ide或文本编辑器中创建一个新的python文件,把此文件命名为python\_database.py
首先,将sqlite模块导入到我们的项目中:
import sqlite3
由于python内置了sqlite3,不需要安装任何东西。接下来,需要创建数据库和与文件的连接。
db = sqlite3.connect('db.sqlite3')
cursor = db.cursor()
上面的代码分配了两个变量,第一个变量db调用了sqlite3.connect,它会连接到文件,这里在括号内告诉python我们想要命名数据库。
cursor变量设置为db.cursor(),python使用它来读取和写入数据库文件表。
然后需要实际创建表,可以通过以下代码来完成:
cursor.execute(''' create table if not exists contacts( id integer primary key, firstname text, lastname text, age text, address text, jobtitle text)''') db.commit()
解释一下上面的代码:
调用cursor.execute
来在db.sqlite3
数据库文件中写入一个新表。创建的表名为contacts
,create table if not exists
行创建表(如果它还不存在于你的python文件目录中)。
下面几行分配表头名称给每列,还必须指定每列中将放入什么类型的数据。
下面列出了不同的数据类型:
null
,该值是个null值。integer
,该值是个有符号整数,根据值的大小,以1、2、3、4、6或8个字节的形式存储。real
,该值是个浮点值,存储为8个字节的ieee浮点数。text
,该值是个文本字符串,使用数据库编码(utf-8、utf-16be或utf-16le)存储。blob
,该值是数据的二进制大对象,以原始形式存储。
有一个名为id
的列,为其分配了integer primary key
值。这对数据库来说是必需的,以便为每个条目分配唯一的id,sqlite会自动增加每个新条目,每次添加新条目时sqlite都会自动将每个条目递增1。(在创建其他表之间的关系时,也需要使用此功能)。
创建的下一组标题包括firstname
、lastname
、age
、address
和jobtitle,
由此构建一个简单的联系人数据库,调用db.commit()
将表提交到数据库文件中。
现在向新表中输入一些假数据,可以编写一些 sql 代码,如下所示:
cursor.execute('''insert into contacts(firstname, lastname, age, address, jobtitle) values (?, ?, ?, ?, ?)''', ('grant', 'peach', '35', '1 smith street', 'software dev'))
db.commit()
如果运行上面的代码,python将执行sql并把条目插入到表中正确的标题中。
为了使它变得稍微简单一些,下面画了一个图表,说明了它是如何工作的:
每个?
都是一个占位符,用于向标题输入条目,因此也可以使用变量来输入数据,例如来自用户输入等。
sqlite数据库阅读器
如果想知道数据是否输入到数据库中,可以通过多种方式检查这一点,但是需要一些其他软件来完成这个操作,这取决于操作系统甚至ide可以使用什么来完成这个操作。
macos sqlite数据库阅读器
base(£19.99或通过setapp获得)
适用于 sqlite 的 db 浏览器(免费)
windows sqlite数据库阅读器
适用于 sqlite 的 db 浏览器(免费)
sqlite阅读器(升级需要费用)
linux sqlite数据库阅读器
适用于 sqlite 的 db 浏览器(免费)
安装其中一个阅读器,并加载数据库文件,应该会看到类似于下面屏幕截图的gui:
并且能够看到创建的表以及所有的标题,如果单击浏览数据选项卡,就会看到表格中包含通过代码分配给每个标题的内容,如下所示:
db browser是编辑数据以及通过csv文件加载大量数据的真正有用工具,也可以在具有专业版的pycharm ide中执行此操作。
查找数据
现在已经知道如何输入数据以及查看它是否实际位于我们的数据库中,来返回到代码并创建一个函数,可以搜索数据库并显示输出。
删除代码中的数据输入部分,因为我们不再需要它(或者直接注释),构建搜索函数,此函数将搜索任何给定的第一个名字并返回该行数据。
def search_db(first_name): cursor.execute("select * from contacts where firstname like '%' || ? || '%'", (first_name,)) results = cursor.fetchall() print('results found...\n') print(results) search_db('grant')
运行上面的代码会输出以下内容:
解释一下代码:
cursor.execute("select * from contacts where firstname like '%' || ? || '%'", (first_name,))
上面的代码从 contacts
表中选择所有内容,其中 firstname
列中包含搜索到的首字母。然后创建了一个叫做results
的变量,通过 cursor.fetchall()
将结果分配给该变量,然后在终端中打印出结果。
以上就是使用python连接sqlite数据库的操作步骤的详细内容,更多关于python连接sqlite的资料请关注代码网其它相关文章!
发表评论