python如何编写数据库_如何在几分钟内用Python编写一个简单的玩具数据库

news/2024/7/7 21:40:12

python如何编写数据库

MySQL, PostgreSQL, Oracle, Redis, and many more, you just name it — databases are a really important piece of technology in the progress of human civilization. Today we can see how valuable data are, and so keeping them safe and stable is where the database comes in!

MySQL,PostgreSQL,Oracle,Redis等等,只是您的名字-数据库是人类文明进步中非常重要的技术。 今天,我们看到了有价值的数据 ,因此确保数据的安全和稳定是数据库的用武之地!

So we can see how important databases are as well. For a quite some time I was thinking of creating My Own Toy Database just to understand, play around, and experiment with it. As Richard Feynman said:

因此,我们可以看到数据库的重要性。 在相当长的一段时间里,我一直在考虑创建“我自己的玩具数据库”,以便理解,试用和试验它。 正如理查德·费曼(Richard Feynman)所说:

“What I cannot create, I do not understand.”

“我不能创造的东西,我不明白。”

So without any further talking let’s jump into the fun part: coding.

因此,我们无需赘言,直接进入有趣的部分:编码。

让我们开始编码… (Let’s Start Coding…)

For this Toy Database, we’ll use Python (my favorite ❤️). I named this database FooBarDB (I couldn’t find any other name ?), but you can call it whatever you want!

对于此玩具数据库,我们将使用Python (我最喜欢的❤️)。 我将此数据库命名为FooBarDB (我找不到其他名称吗?),但是您可以随意调用它!

So first let’s import some necessary Python libraries which are already available in Python Standard Library:

因此,首先让我们导入一些必要的Python库,这些库已在Python标准库中提供:

import json
import os

Yes, we only need these two libraries! We need json as our database will be based on JSON, and os for some path related stuff.

是的,我们只需要这两个库! 我们需要json因为我们的数据库将基于JSON,而os用于一些与路径相关的东西。

Now let’s define the main class FoobarDB with some pretty basic functions, which I'll explain below.

现在,我们用一些非常基本的功能定义主类FoobarDB ,下面将对其进行解释。

class FoobarDB(object):def __init__(self , location):self.location = os.path.expanduser(location)self.load(self.location)def load(self , location):if os.path.exists(location):self._load()else:self.db = {}return Truedef _load(self):self.db = json.load(open(self.location , "r"))def dumpdb(self):try:json.dump(self.db , open(self.location, "w+"))return Trueexcept:return False

Here we defined our main class with an __init__ function. Whenever creating a Foobar Database we only need to pass the location of the database. In the first __init__ function we take the location parameter and replace ~ or ~user with user’s home directory to make it work intended way. And finally, put it in self.location variable to access it later on the same class functions. In the end, we are calling the load function passing self.location as an argument.

在这里,我们使用__init__函数定义了主类。 每当创建Foobar数据库时,我们只需要传递数据库的位置即可。 在第一个__init__函数,我们采取的位置参数,更换~~user与用户的主目录,使其工作目的的方式。 最后,将其放在self.location变量中,以便以后在相同的类函数上对其进行访问。 最后,我们调用将self.location作为参数传递的load函数。

. . . .def load(self , location):if os.path.exists(location):self._load()else:self.db = {}return True
. . . .

In the next load function we take the location of the database as a param. Then check if the database exists or not. If it exists, we load it with the _load() function (explained below). Otherwise, we create an empty in-memory JSON object. And finally, return true on success.

在下一个load函数中,我们将数据库的位置作为参数。 然后检查数据库是否存在。 如果存在,则使用_load()函数加载它(如下所述)。 否则,我们将创建一个空的内存中JSON对象。 最后,成功返回真。

. . . . def _load(self):self.db = json.load(open(self.location , "r"))
. . . .

In the _load function, we just simply open the database file from the location stored in self.location. Then we transform it into a JSON object and load it into self.db variable.

_load函数中,我们只需从存储在self.location的位置打开数据库文件。 然后我们将其转换为JSON对象,并将其加载到self.db变量中。

. . . .def dumpdb(self):try:json.dump(self.db , open(self.location, "w+"))return Trueexcept:return False. . . .

And finally, the dumpdb function: its name says what it does. It takes the in-memory database (actually a JSON object) from the self.db variable and saves it in the database file! It returns True if saved successfully, otherwise returns False.

最后, dumpdb函数:其名称说明了它的作用。 它从self.db变量中获取内存数据库(实际上是JSON对象),并将其保存在数据库文件中! 如果成功保存,则返回True ,否则返回False。

使它更有用……? (Make It a Little More Usable… ?)

Wait a minute! ? A database is useless if it can’t store and retrieve data, isn’t it? Let’s go and add them also…?

等一下! ? 数据库无法存储和检索数据是没有用的,不是吗? 我们也去添加它们吧...?

. . . .def set(self , key , value):try:self.db[str(key)] = valueself.dumpdb()return Trueexcept Exception as e:print("[X] Error Saving Values to Database : " + str(e))return Falsedef get(self , key):try:return self.db[key]except KeyError:print("No Value Can Be Found for " + str(key))  return Falsedef delete(self , key):if not key in self.db:return Falsedel self.db[key]self.dumpdb()return True
. . . .

The set function is to add data to the database. As our database is a simple key-value based database, we’ll only take a key and value as an argument.

set功能是将数据添加到数据库。 由于我们的数据库是一个简单的基于键值的数据库,因此我们仅将keyvalue作为参数。

First, we’ll try to add the key and value to the database and then save the database. If everything goes right it will return True. Otherwise, it will print an error message and return False. (We don’t want it to crash and erase our data every time an error occurs ?).

首先,我们将尝试将键和值添加到数据库中,然后保存数据库。 如果一切正常,它将返回True。 否则,它将打印一条错误消息并返回False。 (我们不希望它在每次发生错误时崩溃并擦除我们的数据吗?)。

. . . .def get(self, key):try:return self.db[key]except KeyError:return False
. . . .

get is a simple function, we take key as an argument and try to return the value linked to the key from the database. Otherwise False is returned with a message.

get是一个简单的函数,我们将key作为参数,并尝试从数据库返回链接到key的值。 否则返回False并显示一条消息。

. . . .def delete(self , key):if not key in self.db:return Falsedel self.db[key]self.dumpdb()return True. . . .

delete function is to delete a key as well as its value from the database. First, we make sure the key is present in the database. If not we return False. Otherwise, we delete the key with the built-in del which automatically deletes the value of the key. Next, we save the database and it returns false.

delete功能是从数据库中删除键及其值。 首先,我们确保密钥存在于数据库中。 如果不是,则返回False。 否则,我们将使用内置的del删除键,该键会自动删除键的值。 接下来,我们保存数据库,并返回false。

Now you might think, what if I’ve created a large database and want to reset it? In theory, we can use delete — but it's not practical, and it’s also very time-consuming! ⏳ So we can create a function to do this task...

现在您可能会想,如果我创建了一个大型数据库并希望将其重置该怎么办? 从理论上讲,我们可以使用delete但它不切实际,而且非常耗时! ⏳因此我们可以创建一个函数来执行此任务...

. . . . def resetdb(self):self.db={}self.dumpdb()return True
. . . .

Here’s the function to reset the database, resetdb! It's so simple: first, what we do is re-assign our in-memory database with an empty JSON object and it just saves it! And that's it! Our Database is now again clean shaven.

这是重置数据库的功能, resetdb ! 很简单:首先,我们要做的是使用空的JSON对象重新分配内存数据库,然后将其保存! 就是这样! 现在,我们的数据库再次被剃干净。

终于……? (Finally… ?)

That’s it friends! We have created our own Toy Database ! ?? Actually, FoobarDB is just a simple demo of a database. It’s like a cheap DIY toy: you can improve it any way you want. You can also add many other functions according to your needs.

就是朋友! 我们已经创建了自己的玩具数据库 ! ?? 实际上, FoobDB只是数据库的简单演示。 这就像一个廉价的DIY玩具:您可以根据需要进行任何改进。 您还可以根据需要添加许多其他功能。

Full Source is Here ? bauripalash/foobardb

完整资料在这里? bauripalash / foobardb

I hope, you enjoyed it! Let me know your suggestions, ideas or mistakes I’ve made in the comments below! ?

我希望你喜欢它! 让我知道您在以下评论中提出的建议,想法或错误! ?

Follow/ping me on socials ? Facebook, Twitter, Instagram

关注/对我进行社交吗? 脸书, 写真, 照片

Thank you! See you soon!

谢谢! 再见!



If You Like My Work (My Articles, Stories, Softwares, Researches and many more) Consider Buying Me A Coffee ☕ 🤗

如果您喜欢我的作品(我的文章,故事,软件,研究等等),请考虑给我买杯咖啡。

翻译自: https://www.freecodecamp.org/news/how-to-write-a-simple-toy-database-in-python-within-minutes-51ff49f47f1/

python如何编写数据库


http://lihuaxi.xjx100.cn/news/238504.html

相关文章

开发自己的山寨Android注解框架

目录 开发自己的山寨Android注解框架开发自己的山寨Android注解框架 参考 Github黄油刀 Overview 在上一章我们学习了Java的注解(Annotation),但是我想大家可能感觉,虽然理解了也会学会,但是不知道干什么用,那么请继续忍受我这枯燥…

Android发布项目到外部仓库

为什么80%的码农都做不了架构师?>>> 关于android发布仓库到外部项目的文章,目前大概为分两类: 一种是发布到bintray、jcenter上,一种是将项目上传到github,然后利用jitpack自动打包,下面简单说…

哈希函数是什么,在区块链中有什么用

想知道更多关于区块链技术知识,请百度【链客区块链技术问答社区】 链客,有问必答!!哈希函数是什么? 哈希函数,又叫散列函数、散列算法,是一种从任何一种数据中创建小的数字“指纹”(…

Web漏洞扫描(一:利用WVS进行漏洞扫描)

任务一、利用WVS进行漏洞扫描 1.1、Acunetix WVS 的下载与安装; 1.1.1、WVS的安装(按照图中的指示执行); 1.1.2、勾选“Create a desktop shortcut”创建桌面图标,然后点击“Next”,选择“Install”&#…

如何在JavaScript中检测用户的首选配色方案

by Oskar Hane由Oskar Hane 如何在JavaScript中检测用户的首选配色方案 (How to detect a user’s preferred color scheme in JavaScript) In recent versions of macOS (Mojave) and Windows 10, users have been able to enable a system level dark mode. This works well…

以太坊系列之账户管理

想知道更多关于区块链技术知识,请百度【链客区块链技术问答社区】 链客,有问必答!!账户 以太坊有两种账户类型: 外部账户(EOA) 合约账户 所有账户的状态代表以太坊网络的状态,以太坊…

玩转“网上邻居”之网络配置(二)

接上篇二、混合系统网络目前实际应用中单一系统的对等网络已不是主流,主要是由于这种网络性能较低,缺乏很好看安全及网络管理能力。目前在各企事业单位中普遍应用的还是基于多系统的域结构混合网络。但因目前主流应用的系统比较多,所以各种网…

win2d 图片水印

win2d 图片水印 本文告诉大家如何使用 win2d 给图片加上水印。 安装 首先需要使用 Nuget 安装 win2d ,安装参见win10 uwp win2d 如果没有更新 dot net core 那么在运行可能会出现下面异常System.TypeLoadException: Requested Windows Runtime type Microsoft.Graph…