在Python中操作SQLite数据库
SQLite是一个基于SQL语言的关系数据库管理系统;它是一个无服务器零配置数据库引擎。
它是最受欢迎的数据库引擎之一,很容易用于小型应用程序。
它仅创建一个磁盘文件来存储整个数据库,这使得文件可移植。
它用于Android操作系统作为存储数据的主要源。
它也被Google Chrome用于存储数据和用户数据,包括本地计算机中的密码。
Python中使用SQLite数据库
在本教程中,将介绍的主题是:在SQLite表中插入图像,列出数据库中存在的表,识别自数据库已连接以来的总更改,备份数据库,转储SQLite数据库,在SQLite中回滚,删除从表中记录,删除表和SQLite数据库异常。
我们可能还希望看到本教程的第一部分,它介绍了SQLite的基础,使用它的优势,连接到数据库文件,在数据库中创建表,将数据插入表中,从表中查询数据,从表中查询数据,更新表格等等。
SQLite数据库中的文件和图像
在使用数据库时,我们需要将图像或者文件插入数据库或者从中导出的情况。
例如,如果要创建要存储员工数据的数据库,我们可能还需要在数据库中插入每个员工的图片。
要在SQLite数据库中添加图像,我们需要使用SQLite的Blob数据类型。
Blob()数据类型用于存储大型对象,通常是大文件,如图像,音乐,视频,文档,pdf等。
第一步是将数据和图像转换为python的字节对象,这类似于sqlite的blob数据类型。
在继续之前,在数据库中创建一个名为Student的表,其中包含字段ID,名称,图像,标记。
运行以下代码以创建表。
import sqlite3 conn = sqlite3.connect("sample.db") print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") table = cur.execute(""" CREATE TABLE student( id INT PRIMARY KEY, name TEXT, images BLOB, marks TEXT ); """) print("\n [+] The table has been created successfully") cur.close() conn.commit() conn.close()
此程序将创建一个带名称学生的新表。
我们将看到终端中的以下输出。
插入图像
要在SQLITE数据库中插入图像,请将图像转换为Python字节对象中的图像,然后将其插入图像列,接受BLOB数据。
使用以下代码使用python在数据库中添加图像img.png。
import sqlite3 conn = sqlite3.connect("sample.db") conn.text_factory = str print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") with open("img.png","rb") as file: data = file.read() python_tuple = (101,"robin",data,"90") print("\n [+] The image has been successfully imported") print("\n [+] Now inserting in the database") cur.execute("INSERT INTO student (id,name,images,marks) VALUES (?,?,?,?)", python_tuple) print("\n [+] The Data has been inserted Successfully ") cur.close() conn.commit() conn.close()
此程序将将图像插入我们创建的学生数据库中。
我们将看到以下输出。
在上面的程序中,我们已以二进制模式打开文件,并在每个字节中读取每个字节并将其存储在变量数据中。
然后我们在INSERT语句中使用该变量在数据库中插入图像。
检索图形
要从数据库中检索图像,请使用SELECT语句获取行,然后将图像的二进制数据访问到Python变量中,该变量将存储在图像文件中。
有关插图,请参阅以下代码。
import sqlite3 conn = sqlite3.connect("sample.db") conn.text_factory = str print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") print("\n [+] Retrieving the image") cur.execute("SELECT * FROM student") ret = cur.fetchall() for i in ret: data = i[2] with open("img2.png","wb") as file: file.write(data) print("\n [+] The image has been saved") cur.close() conn.commit() conn.close()
这个简单的程序将从数据库中检索图像,并将其保存在名为Img2.png的磁盘中。
我们还可以选择图像文件的其他名称。
列出数据库的所有表
在数据库中,我们可以创建许多数量的表。
因此,还需要列出数据库中存在的所有表。
要列出数据库中存在的表,请使用SQL的SELECT语句查询SQLITE_MASTER表。
查询的语法将是:
SELECT name FROM sqlite_master WHERE type='table'
以下是我们如何使用此查询来列出数据库中存在的所有表。
import sqlite3 conn = sqlite3.connect("sample.db") print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") cur.execute("SELECT name from sqlite_master where type='table'") rows = cur.fetchall() print(rows) cur.close() conn.commit() conn.close()
上面的代码将列出数据库中存在的所有表。
执行时代码产生的输出如下。
我们可能会看到一些其他输出,具体取决于我们在数据库中创建的表。
识别自连接到数据库以来的更改
在任何情况下,要识别自数据库已连接以来已修改,插入或者删除的行数是有用的。
为此,请使用连接对象的total_changes()方法,这将返回自连接以来受影响的数据库行的总数。
让我们看到一个示例演示了解它是如何工作的。
import sqlite3 conn = sqlite3.connect("sample.db") conn.text_factory = str print("\n [+] Successfully connected to both the database") cur = conn.cursor() print("\n [+] Both the Cursor has been set up successfully") cur.execute("INSERT INTO student (id, name, images, marks) VALUES (140, 'David',' ',99 )") cur.execute("INSERT INTO student (id, name,images, marks) VALUES (150, 'Sam', ' ', 97)") changes = conn.total_changes print("\n [+] Total now of rows changes is :",changes) conn.commit() cur.close() conn.close()
上述程序将打印当前连接中的行数更改。
在SQLite中回滚
何时撤消某些任务时,可以使用Roldback()函数。
此方法可用于撤消在最后一次提交后完成的任务。
import sqlite3 conn = sqlite3.connect("sample.db") conn.text_factory = str print("\n [+] Successfully connected to both the database") cur = conn.cursor() print("\n [+] Both the Cursor has been set up successfully") cur.execute("INSERT INTO student (id, name, images, marks) VALUES (100001, 'David',' ',99 )") cur.execute("INSERT INTO student (id, name,images, marks) VALUES (100002, 'Sam', ' ', 97)") conn.commit() print("\n [+] The Two row has been inserted successfully") cur.execute("SELECT * FROM student") first = cur.fetchall() print("\n [+] The new records in the database are :") for i in first: print(i) cur.execute("INSERT INTO student (id, name, images, marks) VALUES (10003, 'Kishan', ' ', 100)") cur.execute("INSERT INTO student (id, name, images, marks) VALUES (10004, 'Ankit', ' ', 100)") print("\n [+] The Two row has been inserted successfully but not committed") conn.rollback() print("\n [+] We have roll back the previous commands so the new data will not been inserted") conn.commit() cur.execute("SELECT * FROM student") second = cur.fetchall() print("\n [+] The new records in the database are :") for i in second: print(i) cur.close() conn.close()
在上面的示例中,前两个插入语句将根据给定的数据插入数据,但最后两个插入语句将是回滚,因此它们不会将任何数据添加到表中。
备份数据库
在使用数据库的同时,拍摄数据库的备份是必要的。
SQLite3模块提供备份数据库的函数。
使用连接对象的备份()方法,我们可以备份SQLite数据库。
备份方法的基本语法是:
backup(target, *, pages=0, progress=None, name="main", sleep=0.250)
默认情况下,或者页面所或者 0
或者负整数,整个数据库在单个步骤中复制,这对于小型数据库是优选的;否则,该方法在可以使用广泛的数据库执行的时间执行循环复制到页面。
名称参数显示将复制的数据库名称:它必须是包含默认数据库的默认数据库的字符串,或者指示临时数据库。
睡眠参数指定在尝试备份剩余页面之间才能睡眠的时间。
它可以是整数或者浮点值。
import sqlite3 conn_main = sqlite3.connect("sample.db") conn_backup = sqlite3.connect("sample_backup.db") print("\n [+] Successfully connected to both the database") cur_main = conn_main.cursor() cur_backup = conn_backup.cursor() print("\n [+] Both the Cursor has been set up successfully") conn_main.backup(conn_backup, pages=0, progress=None, name="main") print("The database has been backup successfully") cur_main.close() cur_backup.close() conn_main.commit() conn_backup.commit() conn_main.close() conn_backup.close()
在上面的代码中,两个数据库已连接,一个是我们想要制作备份的数据库,第二个数据库是我们将备份备份的数据库。
使用第一个数据库连接对象的备份()方法进行备份。
此函数接受第二个数据库的连接对象作为在其他数据库上创建备份的目标。
使用页面= 0参数,因此该过程将在一步中进行,这是建议小型数据库的。
此程序将创建一个新的数据库名称sample_backup.db并使用第一个数据库的备份填充它。
我们可能会看到在当前文件夹中创建了一个新数据库,其中文件大小与上一个相同。
转储SQLite数据库
转储数据库是一项重要任务。
通常,转储文件是数据的一组SQL语句,其通常用于备份。
我们可以使用dump()方法转储数据库。
请参阅以下示例以了解如何删除SQLite数据库。
import sqlite3 con = sqlite3.connect("database.db") with open('dump.sql', 'w') as f: for line in con.iterdump(): f.write('%s\n' % line)
上面的程序将转储数据库示例.db,它将将转储数据保存到名为dump.sql的文件中。
我们可以看到Python文件当前的目录中存在的数据,并使用任何文本编辑器打开它。
sqlite3的执行方法3
ExecuteMany()方法针对序列SEQ_OF_PA内存ETERS中的所有参数序列或者映射执行SQL命令。
为简单起见,此方法可用于在一行中执行大多数SQL命令。
例如,我们可以使用此命令通过Python列表插入任意行。
请参阅以下示例为插图。
import sqlite3 conn = sqlite3.connect("sample.db") print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") python_list = [(10000000 ,'vivek',' ','10'), (100000001,'rose',' ','21'), (100000002,'robin',' ','31'), (100000003,'Dev',' ','4'), (100000004,'michael',' ','52') ] cur.executemany("INSERT INTO student (id, name, images, marks) VALUES (?,?,?,?)",python_list) print("\n [+] All the Data has been inserted Successfully ") cur.close() conn.commit() conn.close()
上面的程序将插入Python列表中给出的所有数据。
从表中删除记录
我们可以使用删除操作删除表中的记录。
我们可以使用Where子句使用删除操作快速删除行。
删除语句的基本语法是:
DELETE from table_name WHERE some_condition;
让我们看一个例子。
我们将删除来自我们数据库的员工表中的ID 1001行。
import sqlite3 conn = sqlite3.connect("sample.db") conn.text_factory = str print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") cur.execute("DELETE FROM student WHERE id=1001") print("\n [+] The row has been deleted Successfully ") cur.execute("SELECT * FROM student") data = cur.fetchall() for row in data: print(row) cur.close() conn.commit() conn.close()
上面的代码将删除具有ID 1001的行。
我们可以从删除行已删除的Select语句的返回中查看。
程序的输出如下所示。
删除表
我们可以使用SQLite Drop语句快速删除表。
DROP语句的语法如下所示:
DROP table table_name
如果表格不存在,则SQLite会抛出错误,从而防止此操作,我们可以使用IF存在标记使用DROP语句。
请参阅以下语法:
DROP table if exists table_name
让我们了解如何使用Python SQLite3模块使用此语句来删除表。
在此程序中,我们将删除我们之前创建的学生表。
import sqlite3 conn = sqlite3.connect("sample.db") conn.text_factory = str print("\n [+] Successfully connected to the database") cur = conn.cursor() print("\n [+] Cursor has been set up successfully") cur.execute("DROP TABLE IF EXISTS student") print("\n [+] The table has been drop successfully") cur.close() conn.commit() conn.close()
上面的程序将从示例数据库中删除表学生。
我们可以使用前面看到的列表表命令查看该表是否已删除。
程序的输出如下所示。
SQLite数据库例外
由于某些错误,可能会提出一些SQLite数据库异常。
让我们看看那些错误的错误。
- sqlite3.warning:它是异常的子类。这个例外显示了一些警告,在许多情况下可以忽略这些警告。
- sqlite3.Error:它也是例外的子类。它是SQLite3模块中的所有其他异常的基类。
- sqlite3.databaseerror:这些是由于数据库中的某些错误导致的错误。例如: - 如果我们尝试连接到加密的数据库或者错误的数据库文件,那么它将显示数据是加密的数据库错误,或者不是有效的数据库文件。
- sqlite3.integryError:此异常是DatabaseError的子类。当数据库的关系完整性受到影响时,我们将获得此异常,例如,外键检查失败。
- sqlite3.programmingError:此异常也是DatabaseError的子类。由于编程错误,例如,创建一个具有相同名称的表,这些异常提出了一个已经存在的表,SQL查询中的语法错误等。
- sqlite3.operationalError:它也是DatabaseError的子类。此异常为数据库操作相关的错误提出了错误,并且不在我们的控制中。例如,意外断开WIT系统,服务器向下,发生超时,数据源问题,机器关闭等。
- sqlite3.notsupportedError:当数据库不支持使用的数据库API时,提出了此异常。
这是所有SQLite例外的列表;我们可以使用Python的基本尝试/除错误处理方法来处理我们的程序中的这些例外。