Python与数据库的交互问题小结

MongoDB

安装模块pip install pymongo

连接数据库

import pymongo
 
client = pymongo.MongoClient()
db = client["database_name"]  # 跟上数据库名
collection = db["set_name"]  # 指定集合名

增删改查

添加--->insert_one | insert_many

collection.insert_one({"name":"kongshang","age":12})

查找--->find | find_one

collection.find()

注意要用list转换得到的数据

修改--->update_one | update_many

collection.update_one({"name":"kongshang"},{'$set':{"age":13}})

删除--->delete_one | delete_many

collection.delete_one({"name":"kongshang"})

封装

import pymongo
 
 
class MyMonDB:
    def __init__(self, database, collection):  # 数据库及集合
        self.client = pymongo.MongoClient()  # 连接数据库使用
        self.db = self.client[database]  # 指定使用的数据库
        self.col = self.db[collection]  # 指定使用的集合
 
    def insert(self, data, onlyOne=True):  # onlyOne用来控制插入单条还是多条数据
        if onlyOne:
            self.col.insert_one(data)
        else:
            self.col.insert_many(data)
    
        def find(self, query=None, onlyOne=True):  # query是查询条件
        if onlyOne:
            ret = self.col.find_one(query)
            return ret
        else:
            ret = self.col.find(query)
            return list(ret)
 
    def update(self, data_old, data_new, onlyOne=True):
        if onlyOne:
            self.col.update_one(data_old, {"$set": data_new})
        else:
            self.col.update_many(data_old, {"$set": data_new})
 
    def delete(self, data, onlyOne=True):
        if onlyOne:
            self.col.delete_one(data)
        else:
            self.col.delete_many(data) 

注意该数据库对大小写敏感

MySQL

安装模块pip install pymysql

连接数据库

import pymysql
# 连接mysql
db_config = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "admin",
    "password": "qwe123",
    "db": "stu",  # 指定操作的数据库
    "charset": "utf8"
}
 
conn = pymysql.connect(**db_config)  # mysql登录 **是字典拆包
print(conn)

执行操作

cur = conn.cursor()  # 返回一个执行数据库命令游标对象,通过游标对象执行SQL命令
cur.execute("INSERT INTO stu (id, name) VALUES (1, 'nihao'),(2, 'ci')")  # 执行SQL命令执行插入命令
conn.commit()  # 事务,提交保存
cur.close()  # 关闭游标对象
conn.close()  # 关闭数据库

查询数据

cur.execute("SELECT * FROM stu")  # 执行SQL命令
# print(list(cur))
# print(cur.fetchone())  # 查询单条
# print(cur.fetchmany(3))  # 查询多条
print(cur.fetchall())  # 查询所有

异常处理

try:
    cur.execute("INSERT INTO stu (id, name) VALUES (1, 'nihao'), (2, 'ci')")
except Exception as e:
    print(e)
    conn.rollback()  # 事务回滚
else:
    conn.commit()  # 事务提交
finally:
    cur.close()  # 关闭游标对象
    conn.close()  # 关闭数据库

Redis

安装模块pip install redis

连接数据库

import redis
 
# 登录数据库
# host ip地址
# decode_responses get获得键值时 True返回字符串数据,默认是False二进制数据
# db 指定数据库,默认为1
red = redis.StrictRedis(host="127.0.0.1", decode_responses=True, db=2)

执行操作

# 字符串
red.set("num", 1)
print(red.get("num"))
print(red.type("num"))
red.delete('num')
# 综上,调用Redis数据库的方法是red.[输入redis数据库操作命令]()