欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python與數(shù)據(jù)庫(kù)的交互問(wèn)題小結(jié)

 更新時(shí)間:2021年12月25日 11:11:13   作者:A-L-Kun  
這篇文章主要介紹了Python與數(shù)據(jù)庫(kù)的交互,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

MongoDB

安裝模塊pip install pymongo

連接數(shù)據(jù)庫(kù)

import pymongo
 
client = pymongo.MongoClient()
db = client["database_name"]  # 跟上數(shù)據(jù)庫(kù)名
collection = db["set_name"]  # 指定集合名

增刪改查

添加--->insert_one | insert_many

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

查找--->find | find_one

collection.find()

注意要用list轉(zhuǎn)換得到的數(shù)據(jù)

修改--->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):  # 數(shù)據(jù)庫(kù)及集合
        self.client = pymongo.MongoClient()  # 連接數(shù)據(jù)庫(kù)使用
        self.db = self.client[database]  # 指定使用的數(shù)據(jù)庫(kù)
        self.col = self.db[collection]  # 指定使用的集合
 
    def insert(self, data, onlyOne=True):  # onlyOne用來(lái)控制插入單條還是多條數(shù)據(jù)
        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) 

注意該數(shù)據(jù)庫(kù)對(duì)大小寫(xiě)敏感

MySQL

安裝模塊pip install pymysql

連接數(shù)據(jù)庫(kù)

import pymysql
# 連接mysql
db_config = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "admin",
    "password": "qwe123",
    "db": "stu",  # 指定操作的數(shù)據(jù)庫(kù)
    "charset": "utf8"
}
 
conn = pymysql.connect(**db_config)  # mysql登錄 **是字典拆包
print(conn)

執(zhí)行操作

cur = conn.cursor()  # 返回一個(gè)執(zhí)行數(shù)據(jù)庫(kù)命令游標(biāo)對(duì)象,通過(guò)游標(biāo)對(duì)象執(zhí)行SQL命令
cur.execute("INSERT INTO stu (id, name) VALUES (1, 'nihao'),(2, 'ci')")  # 執(zhí)行SQL命令執(zhí)行插入命令
conn.commit()  # 事務(wù),提交保存
cur.close()  # 關(guān)閉游標(biāo)對(duì)象
conn.close()  # 關(guān)閉數(shù)據(jù)庫(kù)

查詢數(shù)據(jù)

cur.execute("SELECT * FROM stu")  # 執(zhí)行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()  # 事務(wù)回滾
else:
    conn.commit()  # 事務(wù)提交
finally:
    cur.close()  # 關(guān)閉游標(biāo)對(duì)象
    conn.close()  # 關(guān)閉數(shù)據(jù)庫(kù)

Redis

安裝模塊pip install redis

連接數(shù)據(jù)庫(kù)

import redis
 
# 登錄數(shù)據(jù)庫(kù)
# host ip地址
# decode_responses get獲得鍵值時(shí) True返回字符串?dāng)?shù)據(jù),默認(rèn)是False二進(jìn)制數(shù)據(jù)
# db 指定數(shù)據(jù)庫(kù),默認(rèn)為1
red = redis.StrictRedis(host="127.0.0.1", decode_responses=True, db=2)

執(zhí)行操作

# 字符串
red.set("num", 1)
print(red.get("num"))
print(red.type("num"))
red.delete('num')
# 綜上,調(diào)用Redis數(shù)據(jù)庫(kù)的方法是red.[輸入redis數(shù)據(jù)庫(kù)操作命令]()

到此這篇關(guān)于Python與數(shù)據(jù)庫(kù)的交互的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)庫(kù)交互內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論