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 ☕

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

  1. github创建静态页面_如何在10分钟内使用GitHub Pages创建免费的静态站点

    github创建静态页面 Static sites have become all the rage, and with good reason – they are blazingly fast a ...

  2. 如何设计一个简单的KV数据库

    下面的内容仅供设计一个简单的KV数据库.如果想要实现一个功能更强的KV数据库的话,还需要考虑:更加丰富的数据类型.数据压缩.过期机制.数据淘汰策略.集群化.高可用等功能,另外还可以增加统计模块.通知模 ...

  3. python搭配什么数据库_教你如何优雅地用Python连接MySQL数据库

    作者 | Python语音识别 来源 | 深度学习与python(ID:PythonDC) 不管是机器学习.web开发或者爬虫,数据库都是绕不过去的.那么今天我们就来介绍Python如何Mysql数据 ...

  4. python只能使用内置数据库_隐藏彩蛋:你知道python有一个内置的数据库吗?

    本文转载自公众号"读芯术"(ID:AI_Discovery). 如果你是软件开发人员,相信你一定知道甚至曾经使用过一个非常轻量级的数据库--SQLite.它几乎拥有作为一个关系数据 ...

  5. python跑得慢_代码跑得慢甩锅Python?手把手教你如何给代码提速30%

    原标题:代码跑得慢甩锅Python?手把手教你如何给代码提速30% 来源丨Medium 编译丨王转转 大数据文摘出品 https://mp.weixin.qq.com/s/bY3REj6qVw0M1N ...

  6. 用python画奥迪标志_不知道不 OK!53 个 Python 经典面试题详解

    作者 | Chris 翻译 | 苏本如,责编 | 夕颜 头图 | CSDN付费下载自视觉中国 出品 | CSDN(ID:CSDNnews) 以下为译文: 本文列出53个Python面试问题,并且提供了 ...

  7. python大神作品_掌握了这24个顶级Python库,你就是大神!

    全文共11815字,预计学习时长24分钟 Python有以下三个特点: · 易用性和灵活性 · 全行业高接受度:Python无疑是业界最流行的数据科学语言 · 用于数据科学的Python库的数量优势 ...

  8. 运维学python用不上_运维工程师为什么要学python?

    现阶段,掌握一门开发语言已经成为高级运维工程师的必备计能,不会开发,你就不能充分理解你们系统的业务流程,你就不能帮助调试.优化开发人开发的程序, 开发人员有的时候很少关注性能的问题,这些问题就得运维人 ...

  9. python 进程生命周期_计算客户生命周期价值的python解决方案

    python 进程生命周期 By Lisa Cohen, Zhining Deng, Shijing Fang, and Ron Sielinski 由丽莎·科恩,志宁邓,石井方和罗恩Sielinsk ...

最新文章

  1. 一个分号将代码效率提升100倍
  2. java-垃圾回收的并行与并发
  3. oracle重新恢复数据库,重新安装oracle根据原数据文件恢复数据库
  4. jpa一级缓存和二级缓存_了解一级JPA缓存
  5. 访问模型参数,初始化模型参数,共享模型参数方法
  6. 庆五一,We7同步发行2.5正式版、2.6 Beta版!
  7. Android 系统(115)---死机问题分析
  8. java操作Linux 调用shell命令,shell脚本
  9. Julia: feather格式和hdf5格式比较
  10. 考研计算机基础综合,考研计算机基础综合
  11. 使用 emoji表情 实现自己的 表情库
  12. 云课堂让职业院校云计算教学更简单
  13. React Antd4 CRA / Next.js / Vite 按需加载组件的 CSS / Less
  14. Fedora core 5.0加载ntfs分区(yum方法)
  15. Nginx出现大量499响应码怎么办?
  16. 区块链笔记 - 1、区块链的来龙去脉
  17. JNI-开发注意细节点
  18. 小乌龟克隆报错:git add not exit cleanly
  19. plt.contour()功用
  20. vue中获取/操作组件中的dom元素

热门文章

  1. 数据结构之【队列】的基本操作C语言实现
  2. 083、Prometheus架构(2019-05-05 周日)
  3. 酷派、华为不能打印log解决办法
  4. ES5-Array-push(),pop(),shift(),unshift()
  5. python基础===拆分字符串,和拼接字符串
  6. GDI+ Bitmap与WPF BitmapImage的相互转换
  7. 轻松记账工程冲刺第二阶段10
  8. symfony2项目访问app_dev.php不显示debug工具栏的问题
  9. 盛大文学难逃“垄断”嫌疑,完美文学虎口夺食
  10. 比特币SPV节点启动流程图