sql 是用于管理数据库的最常用编程语言,由于其稳健性和简单性而在许多大公司中使用。但是如果我们想将它集成到一个更大、更通用的程序中怎么办?这就是对象关系管理器发挥作用的地方!在这篇文章中,我将讨论并展示一些使用 sqlite3 与 sql 数据库通信的基础知识的示例。大部分工作将在专业环境中通过 sqalchemy 等标准化 orm 完成,但了解幕后发生的事情是有好处的。
在开始与数据库对话之前,我们需要将 sqlite3 导入到我们的 python 文件中。
import sqlite3
导入后,我们设置了与数据库的连接以及与之交互的游标。并不是说,如果您尝试连接的文件不存在,此行将在连接之前创建它。
conn = sqlite3.connect('pets.db')
cursor = conn.cursor()
为了在 python 中跟踪数据库信息,我们将创建一个与数据库表中包含的信息相对应的类。对于我们的示例,我们将创建一个宠物数据库供用户跟踪。
class pet:
all = {}
def __init__(self, name, species, id=none):
self.id = id
self.name = name
self.species = species
在此示例中,id、name 和species 是表中的列,该类的每个实例都是一行。我们将使用字典类属性 all 来存储数据库中行的各个实例,这样我们就不必每次引用它们时都从数据库中提取它们。我们将在初始化时将 id 保留为 none,因为它将在我们为对象创建实际数据库条目后分配。
现在我们的框架开始组合在一起,让我们看一些通过我们的类运行 sql 代码来构建和操作数据库的示例。在我们做任何事情之前,我们需要创建一个表。语法与 sql 本身几乎相同,但作为特殊字符串传递给我们的 cursor 以在我们的数据库上运行。
@classmethod
def create_table(cls):
sql = """
create table if not exists pets (
id integer primary key,
name text,
species text)
"""
cursor.execute(sql)
conn.commit()
接下来我们需要能够将信息添加到我们的数据库中。毕竟,没有信息可组织的数据库表算什么?我们将使用类方法“create”来创建实例,并使用实例方法“save”将自身保存到数据库和类中。
@classmethod
def create(cls, name, species):
pet = cls(name, species)
pet.save()
return pet
def save(self):
sql = """
insert into pets (name, species)
values (?, ?)
"""
cursor.execute(sql, (self.name, self.species))
conn.commit()
self.id = cursor.lastrowid
type(self).all[self.id] = self
注意我们写的是“?”符号而不是我们想要在 sql 代码中使用的实际值。 cursor.execute 函数可以识别这些,并将按顺序用我们传递给它的值替换它们。在本例中,为 self.name 和 self.species。然后我们从数据库中获取新插入行的 id,并将其用作实例的 python 字典的键。
现在我们已经掌握了为数据库创建信息的基础知识,我们可以编写一个简短的测试脚本来演示。
from pet import pet
def seed_database():
pet.create_table()
fido = pet.create("fido", "dog")
print(fido)
seed_database()
这会在控制台打印什么?
<pet.pet object at></pet.pet>
我们至少要创建一个对象,让我们更新 pet 类来覆盖基本的打印功能,我们可以使用特殊函数 'repr' 来做到这一点。
def __repr__(self):
return f"<pet>"
</pet>
该函数获取类的实例并返回一个格式化字符串以轻松显示我们的信息。
<pet fido dog></pet>
这表明它正在工作,但是仅使用 python 对象没有什么是做不到的。数据库的明显优点是它被保存到一个单独的文件中,因此您的数据在程序执行之间保持不变。让我们将其分成一个简单的脚本来为数据库播种,以及一个将其打印出来进行演示的脚本。当我们这样做时,我们将向 pet 类添加更多功能。
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
class pet:
# dictionary of objects saved to the database.
all = {}
def __init__(self, name, species, id=none):
self.id = id
self.name = name
self.species = species
def __repr__(self):
return f"<pet>"
@classmethod
def create_table(cls):
""" create a new table to persist the attributes of animal instances """
sql = """
create table if not exists pets (
id integer primary key,
name text,
species text)
"""
cursor.execute(sql)
conn.commit()
@classmethod
def drop_table(cls):
sql = """
drop table if exists pets;
"""
cursor.execute(sql)
conn.commit()
@classmethod
def create(cls, name, species):
""" initialize a new pet instance and save the object to the database """
pet = cls(name, species)
pet.save()
return pet
def save(self):
sql = """
insert into pets (name, species)
values (?, ?)
"""
cursor.execute(sql, (self.name, self.species))
conn.commit()
self.id = cursor.lastrowid
type(self).all[self.id] = self
def update(self):
sql = """
update pets
set name = ?, location = ?
where id = ?
"""
cursor.execute(sql, (self.name, self.location, self.id))
conn.commit()
def delete(self):
sql = """
delete from pets
where id = ?
"""
cursor.execute(sql, (self.id,))
conn.commit()
# delete the dictionary entry using id as the key
del type(self).all[self.id]
# set the id to none
self.id = none
@classmethod
def get_all(cls):
sql = """
select *
from pets
"""
rows = cursor.execute(sql).fetchall()
return [cls.instance_from_db(row) for row in rows]
</pet>
我们的种子脚本:
from pet import pet
def seed_database():
pet.drop_table()
pet.create_table()
fido = pet.create("fido", "dog")
lucy = pet.create("lucy", "turtle")
borris = pet.create("borris", "goldfish")
seed_database()
我们的最终测试脚本会向数据库添加一个条目并显示其内容。
from pet import pet
def add_and_display():
pet.create("bob", "chicken")
for pet in pet.get_all():
print(pet)
add_and_display()
现在,如果我们想重置数据库并给它一些初始值,我们只需运行:
$ python lib/seed.py
我们可以通过运行看到它持续存在:
$ python lib/display.py
<pet fido dog><pet lucy turtle><pet borris goldfish><pet bob chicken></pet></pet></pet></pet>
每次运行显示脚本时,它都会向表中添加另一个 bob!
<pet fido dog><pet lucy turtle><pet borris goldfish><pet bob chicken><pet bob chicken></pet></pet></pet></pet></pet>
这远不是一个好的 orm 的全部内容,但它是一个很好的框架,可以帮助您了解标准化对象关系管理器的底层情况。