[Python]seldom以字典的形式对MySQL数据库的增删查改

作者: xusx 分类: MySQL,Python 发布时间: 2021-05-21 20:43 浏览:316

一、安装seldom、连接MySQL数据库

pip install seldom==2.1.0 # 安装seldom
pip install pymysql # 安装pymysql驱动
# 链接MySQL数据库
from seldom.db_operation import MySQLDB

db = MySQLDB(host="127.0.0.1", 
             port="3306", 
             user="root", 
             password="123", 
             database="db_name")

二、操作方法

1、 删除表数据

db.delete_data(table="user", where={"id":1})

2、 查询表数据

result = db.select_data(table="user", where={"id":1, "name": "tom"})
print(result)

3、 更新表数据

db.update_data(table="user", data={"name":"new tom"}, where={"name": "tom"})

4、 插入一条数据

data = {'id': 1, 'username': 'admin', 'password': "123"},
db.insert_data(table="user", data=data)

5、 批量插入数据(在插入之前先清空表数据),当然也可以循环执行上一句来批量插入数据

datas = {
    'table1': [
        {'id': 1, 'name': '红米Pro发布会'},
        {'id': 2, 'name': '可参加人数为0'},
        {'id': 3, 'name': '当前状态为0关闭'},
        {'id': 4, 'name': '发布会已结束'},
        {'id': 5, 'name': '小米5发布会'},
    ],
    'table2': [
        {'id': 1, 'real_name': 'alen'},
        {'id': 2, 'real_name': 'has sign'},
        {'id': 3, 'real_name': 'tom'},
    ]
}

db.init_table(datas)

6、最后别忘了关闭数据库连接

db.close()

另外,如果你喜欢自己动手写sql的话,可以看看
https://github.com/whiteclover/dbpy

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!