python基础之sqlite3的简单数据库管理

205 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天,点击查看活动详情

介绍

SQLite是一个独立的、基于文件的 SQL 数据库。SQLite 可以与Python捆绑在一起使用,这样你就可以在任何的Python应用程序中来使用它,而且不用安装任何其他软件。

在本教程中,我们将介绍sqlite3Python 3 中的模块。我们将创建到 SQLite 数据库的连接,向该数据库添加一个表,将数据插入该表,并读取和修改该表中的数据。

前情提要

在日常工作中,我一直在使用CVS或者TXT来存储一些数据结果,这样做不仅操作麻烦,而且效率低下,如果使用SQL数据库,这将变得更加容易和标准,它易于使用,易于解析,并且数据文件不太可能损坏/损坏。


import sqlite3 as sql

首先我们打开一个连接。如果要创建新数据库,请命名文件。但是为了在 RAM 中创建一个用于测试的数据库,请给它一个特殊的名称:memory:

# conn: sql.Connection = sql.connect('platonic_solids.db')
conn: sql.Connection = sql.connect(':memory:')

然后,我们还应该在数据库中初始化一个“光标”,以便我们可以读/写。

cursor: sql.Cursor = conn.cursor()

注意: 应关闭连接以保存更改

conn.commit()  # 保存所有更改
conn.close()

写库

nameverticesfaces
tetrehedron44
cube66
octahedron88
dodecahedron1220
icosahedron2012
conn: sql.Connection = sql.connect(':memory:')
cursor: sql.Cursor = conn.cursor()

cursor.execute('CREATE TABLE solids (name TEXT, vertices INTEGER, faces INTEGER)')
solids_list = [('tetrahedron', 4, 4),
               ('cube', 6, 6),
               ('octahedron', 8, 8),
               ('dodecahedron', 12, 20),
               ('icosahedron', 20, 12)]

for entry in solids_list:
    cursor.execute('INSERT INTO solids VALUES (?, ?, ?)', entry)

读数据库

Use .fetchall() or .fetchone().

rows = cursor.execute('SELECT name, vertices, faces FROM solids').fetchall()
rows
[('tetrahedron', 4, 4), ('cube', 6, 6), ('octahedron', 8, 8), ('dodecahedron', 12, 20), ('icosahedron', 20, 12)]

同时你也可以使用where来过滤搜索条件

rows = cursor.execute('SELECT name, vertices, faces FROM solids WHERE (vertices >= 5)').fetchall()
rows
[('cube', 6, 6), ('octahedron', 8, 8), ('dodecahedron', 12, 20), ('icosahedron', 20, 12)]

修改数据库

下面两种方法都可以使用

  1. UPDATE <table> SET <variable> = <value> WHERE <filter>
  2. DELETE FROM <table> WHERE <filter>
cursor.execute('UPDATE solids SET name = ? WHERE vertices=4', ('pyramid', ))
rows = cursor.execute('SELECT name, vertices, faces FROM solids').fetchall()
rows
[('pyramid', 4, 4), ('cube', 6, 6), ('octahedron', 8, 8), ('dodecahedron', 12, 20), ('icosahedron', 20, 12)]

Sqlite3 接受的python数据类型

Python typeSQLite type
NoneNULL
intINTEGER
floatREAL
strTEXT
bytesBLOB

例如:

numbers = [1, 2, 3]
cursor.execute('SELECT ?', (numbers, )).fetchall() # This is supposed to throw an InterfaceError.
---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-9-9d26a0cd79b1> in <module>
      1 numbers = [1, 2, 3]
----> 2 cursor.execute('SELECT ?', (numbers, )).fetchall() # This is supposed to throw an InterfaceError.

InterfaceError: Error binding parameter 0 - probably unsupported type.

解决方法是创建一个假类,然后为该类定义一个适配器和一个转换器函数。

from ast import literal_eval

class NumList(list[int]):
    pass

def adapt_list_of_nums(list_of_nums):
    """Convert list to a type acceptable to SQL."""
    return str(list_of_nums)

def convert_to_list_of_nums(output_from_sql):
    """Get back the list of numbers."""
    return literal_eval(output_from_sql)

sql.register_adapter(NumList, adapt_list_of_nums)
sql.register_converter('NumList', convert_to_list_of_nums)
numbers = NumList([1, 2, 3])
cursor.execute('SELECT ?', (numbers, )).fetchall() # Now it works
[('[1, 2, 3]',)]

快捷方式可以为我们节省大量的打字工作并使代码更紧凑

快捷方式让我们无需cursor对象就可以直接执行命令。例如,在下面的代码块中,我们直接使用连接,根本不使用光标。

conn = sql.connect(':memory:')
conn.execute('create table solids(name, vertices, faces)')

solids_list = [('tetrahedron', 4, 4),
               ('cube', 6, 6),
               ('octahedron', 8, 8),
               ('dodecahedron', 12, 20),
               ('icosahedron', 20, 12)]

conn.executemany('insert into solids(name, vertices, faces) values (?, ?, ?)', solids_list)

for row in conn.execute('select name, vertices, faces from solids'):
    print(row)
    
conn.close()
('tetrahedron', 4, 4)
('cube', 6, 6)
('octahedron', 8, 8)
('dodecahedron', 12, 20)
('icosahedron', 20, 12)