当前位置: 首页 > 编程日记 > 正文

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

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如何编写数据库

相关文章:

齐博cms 7.0 漏洞分析

** 0x01 原理分析 ** 还是很早之前爆出来的漏洞,现在拿出来学习一下,参考阿里巴巴:https://security.alibaba.com/... 漏洞发生在/inc/common.inc.php页面中。首先看这个函数: 首先使用ini_get来获取php.ini中变量register_global…

J2EE 中的服务器 tomcat6.0 配置

Tomcat6.0 配置 第一步:下载jdk和tomcat:JDK下载 Tomcat下载 最新的jdk为1.6.10,tomcat为6.0,建议jdk1.4以上,tomcat4.0以上 第二步:安装和配置你的jdk和tomcat:执行jdk和tomcat的安装程序…

【Ant Design Pro 四】react 点击事件传参

简单的绑定点击事件传参&#xff1a; 点击事件 function myClick(){console.log(点击)}return (<Button onClick{myClick}>点击</Button>) 点击事件传参 sendGoods(e){console.log(sendGoods,e)}render() {retrun(<Button type"primary" onClick{(e…

初创公司为什么要我_在一家大型初创公司担任副总裁之前,我希望知道什么

初创公司为什么要我by Assaf Elovic通过阿萨夫埃洛维奇 在一家大型初创公司担任副总裁之前&#xff0c;我希望知道什么 (What I wish I knew before becoming a VP at a large startup) When I started my position as VP of R&D at a growing startup, I thought my bigg…

微信小程序自定义轮播图滚动样式 自定义组件轮播图的实现

效果图&#xff1a; 实现代码&#xff1a; wxml <view class"card card_b"><swiper autoplay"{{true}}" interval"4000" duration"500" current"{{swiperCurrent}}" bindchange"swiperChange" class&qu…

好看的dialog,sweet Alert Dialog 导入Android Studio

系统自带的dialog实在是丑到无法忍受。所以找到了一款比較好的第三方dialog。 github 地址例如以下: https://github.com/pedant/sweet-alert-dialog 老规矩&#xff0c;还是先看效果图&#xff01; 以下来介绍导入Android studio的方法 首先将github上的项目clone到本地。然后…

linux系统中删除文件夹

rm -rf 文件夹的名称 rm-r 文件名称转载于:https://www.cnblogs.com/chucklu/p/4890523.html

unity开发入门_Unity游戏开发终极入门指南

unity开发入门Unity is a great tool for prototyping everything from games, to interactive visualisations. In this article, we run through all you need to know to get started using Unity.Unity是一个很好的工具&#xff0c;可用于制作从游戏到交互式可视化等所有内…

uvalive 3218 Find the Border

题意&#xff1a;一条封闭折线将平面分成了若干个区域&#xff0c;按顺序给出折线各点的坐标&#xff0c;要求输出封闭折线的轮廓。 题解&#xff1a;用类似卷包裹的算法&#xff0c;先确定一个一定会被选中的点(x坐标最小&#xff0c;y坐标最小)作为起点&#xff0c;然后把可…

[Mac] mac linux 多线程下载利器 axel

​> 之前做过一些文件下载的统计&#xff0c;发现谷歌浏览器chrome和火狐firefox, 一般都是单线程的下载文件&#xff0c;360浏览器却是多线程的下载。如今切换到了mac上&#xff0c;发现没有360哪个浏览器&#xff0c;就像找个在linux或者mac下能够多线程下载的工具。 linu…

antd 表单提交,文件和表单内容一起提交,表单校验

用很简单的源码实现包含下列 antd 表单相关知识: 1.表单必填校验,规则校验 2.Upload 上传图片,获取上传图片的状态,如上传成功,上传失败,上传进度条,删除上传的文件 3.获取 Input 组件用户输入的值,设置默认值 4.提交表单不刷新页面 5.把上传的图片显示在页面 页面…

代码注释//_您应该停止编写//的五个代码注释,并且//应该开始的一个注释

代码注释//提供来自您最喜欢和最受欢迎的开源项目的示例-React&#xff0c;Angular&#xff0c;PHP&#xff0c;Pandas等&#xff01; (With examples from your favorite and most popular open source projects — React, Angular, PHP, Pandas and more!) 代码质量与注释之间…

eclipse安装maven

maven 下载地址&#xff1a;http://maven.apache.org/download.cgi 1.maven环境配置 将下载的maven解压到某一盘下&#xff0c;进入E:\maven\apache-maven-3.3.9\conf目录&#xff0c;修改setting.xml文件 找到<localRepository>节点&#xff0c;配置本地仓库的地址&…

微信小程序 循迹功能制作

规划地图的路径&#xff0c;实时获取用户当前的定位&#xff0c;进行路线循迹导航功能的开发&#xff1a; 效果图&#xff1a; 实现代码&#xff1a; <map id"map" enable-satellite longitude"{{longitude1}}" latitude"{{latitude1}}" sca…

DOM解析和SAX解析的区别

DOM解析和SAX解析的区别 博客分类&#xff1a; XMLDOM SAX DOM解析和SAX解析的区别 No区 别DOM解析SAX解析1操作将所有文件读取到内存中形成DOM树&#xff0c;如果文件量过大&#xff0c;则无法使用顺序读入所需要的文件内容&#xff0c;不会一次性全部读取&#xff0c;不受文件…

java编写代码用什么_如何学习用Java编写代码:为什么要学习以及从哪里开始

java编写代码用什么by John Selawsky约翰塞劳斯基(John Selawsky) 如何学习用Java编写代码&#xff1a;为什么要学习以及从哪里开始 (How to learn to code in Java: why you should and where to start) Define your career goals and choose a language. This is the most i…

迷宫寻宝(搜索)

迷宫寻宝&#xff08;一&#xff09; 时间限制&#xff1a;1000 ms | 内存限制&#xff1a;65535 KB难度&#xff1a;4描述一个叫ACM的寻宝者找到了一个藏宝图&#xff0c;它根据藏宝图找到了一个迷宫&#xff0c;这是一个很特别的迷宫&#xff0c;迷宫里有N个编过号的门&…

理解Python的迭代器(转)

原文地址: http://python.jobbole.com/81916/ 另外一篇文章: http://www.cnblogs.com/kaituorensheng/p/3826911.html 什么是迭代 可以直接作用于for循环的对象统称为可迭代对象(Iterable)。 可以被next()函数调用并不断返回下一个值的对象称为迭代器(Iterator)。 所有的Iterab…

快捷导航动画制作

做了一个仿大众点评的快捷导航动画效果&#xff0c;点击导航内的箭头&#xff0c;导航缩放&#xff0c;点击快捷导航再伸展。 看效果图&#xff1a; 实现代码&#xff1a; <block wx:if"{{!isCustom}}"><view class"home_and_reSource" animati…

instant apps_Android Instant Apps 101:它们是什么以及它们如何工作

instant appsby Tomislav Smrečki通过TomislavSmrečki Android Instant Apps are a cool new way to consume native apps without prior installation. Only parts of the app are downloaded and launched, giving the users a native look and feel in a couple of secon…

数据库分享一: MySQL的Innodb缓存相关优化

无论是对于哪一种数据库来说&#xff0c;缓存技术都是提高数据库性能的关键技术&#xff0c;物理磁盘的访问速度永 远都会与内存的访问速度永远都不是一个数量级的。通过缓存技术无论是在读还是写方面都可以大大提 高数据库整体性能。Innodb_buffer_pool_size 的合理设置Innodb…

用过美德乐吸奶器的宝妈们感觉比国产吸奶器怎么样啊?

药效好不好&#xff0c;看疗效就知道。吸奶器好不好看评价就知道。我们来看看美德乐吸奶器 天猫旗舰店 : http://medela.wang 的宝妈们的评价如可 拔奶神器&#xff0c;绝对好过贝亲&#xff01;最初一次七八十&#xff0c;后来一百多&#xff0c;现在可以翻个倍。结合宝宝吮吸…

小程序地图多个 circles 使用demo

效果图&#xff1a; 代码&#xff1a; var that; const app getApp() const util require("../../utils/util.js") const data require("../../utils/map.js") Page({data: {pageShow: false,scale: 15,obj: {},longitude: 116.34665554470486,latitud…

编写文档_如何通过编写优质文档来使自己的未来快乐

编写文档by Gabriele Cimato加布里埃莱西马托(Gabriele Cimato) 如何通过编写优质文档来使自己的未来快乐 (How to make your future self happy by writing good docs) 或者&#xff0c;在清除旧代码库时如何减少痛苦 (Or how to be less miserable when dusting off an old …

(转载)人人都会OSGI--实例讲解OSGI开发

http://longdick.iteye.com/blog/457310转载于:https://www.cnblogs.com/eecs2016/articles/7422310.html

小程序json字符串转 json对象 { name :你好} 转成 { name :你好}

解决后端接口返回 var obj "{ name :"你好"}" 类似这样的数据&#xff0c;对象或者数组外面包了一层引号&#xff0c; 把这种数据转成 var obj { name :"你好"}&#xff1b; 直接上代码&#xff1a; // pages/test/test.js Page({jsonStrToJ…

每天写的叫工作日志,每周写的总结叫周报,每月写的叫月报

有些时候&#xff0c;老板会突发让您求每天都要写工作周报&#xff0c;什么项目什么任务&#xff0c;完成情况&#xff0c;完成花费的时间等&#xff0c;然后汇总部门周报&#xff1b;也不是写不出&#xff0c;只是不知道有时候重复做一个项目&#xff0c;到底每天有什么好写&a…

为什么分散刷新没有死时间_分散项目为何失败(以及如何处理)

为什么分散刷新没有死时间The most exciting thing about working in the decentralized economy is the fact that no one has any idea as to where it’ll all end up!在去中心decentralized economy工作最令人振奋的事情是&#xff0c;没有人知道最终的结果&#xff01; T…

.NET Core 常用加密和Hash工具NETCore.Encrypt

前言 在日常开发过程中&#xff0c;不可避免的涉及到数据加密解密&#xff08;Hash&#xff09;操作&#xff0c;所以就有想法开发通用工具&#xff0c;NETCore.Encrypt就诞生了。目前NETCore.Encrypt只支持.NET Core ,工具包含了AES,DES,RSA加密解密&#xff0c;MD5&#xff0…

url 通配符解析成参数

需求&#xff1a;url 参数是通配符&#xff0c;需要把通配符解析成参数并且拼接到 url 中 例如&#xff1a;https://xxx.cn/index.html$a1$b2; 解析成 https://xxx.cn/index.html?a1&b2; 时间关系&#xff0c;直接上代码&#xff0c;有时间再补上注释 下面是小程序页…