博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python如何编写数据库_如何在几分钟内用Python编写一个简单的玩具数据库
阅读量:2521 次
发布时间:2019-05-11

本文共 7882 字,大约阅读时间需要 26 分钟。

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 said:

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

“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 jsonimport 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 True    def _load(self):        self.db = json.load(open(self.location , "r"))    def dumpdb(self):        try:            json.dump(self.db , open(self.location, "w+"))            return True        except:            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 True        except:            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)] = value            self.dumpdb()            return True        except Exception as e:            print("[X] Error Saving Values to Database : " + str(e))            return False    def get(self , key):        try:            return self.db[key]        except KeyError:            print("No Value Can Be Found for " + str(key))              return False    def delete(self , key):        if not key in self.db:            return False        del 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 False        del 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 ?

完整资料在这里?

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 ? F T I

关注/对我进行社交吗?

Thank you! See you soon!

谢谢! 再见!



If You Like My Work (My Articles, Stories, Softwares, Researches and many more) Consider 🤗

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

翻译自:

python如何编写数据库

转载地址:http://ftuzd.baihongyu.com/

你可能感兴趣的文章
echarts学习笔记 01
查看>>
PrimeNG安装使用
查看>>
iOS 打包
查看>>
.NET Core中的数据保护组件
查看>>
华为云软件开发云:容器DevOps,原来如此简单!
查看>>
MyEclipse 快捷键(转载)
查看>>
03链栈_LinkStack--(栈与队列)
查看>>
会滚段
查看>>
MANIFEST.MF的用途(转载)
查看>>
react高阶组件
查看>>
Android 高手进阶,自己定义圆形进度条
查看>>
Objective-C路成魔【2-Objective-C 规划】
查看>>
Java之旅(三)--- JSTL和EL表情
查看>>
正则匹配
查看>>
单利模式
查看>>
病毒表-相信对大家都有帮助-病毒词典
查看>>
ios 8 联系人ABPeoplePickerNavigationController
查看>>
列表、字典、append
查看>>
关于JAVA IO流的学习
查看>>
C#使用Json.Net遍历Json
查看>>