这篇教程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 注意要用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# 连接mysqldb_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 指定数据库,默认为1red = 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数据库操作命令]() 到此这篇关于Python与数据库的交互的文章就介绍到这了,更多相关Python数据库交互内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net! Python实现自动玩贪吃蛇程序 通过requests来实现一个京东联盟开放平台API Client |