Python與數(shù)據(jù)庫的交互問題小結(jié)
MongoDB
安裝模塊pip install pymongo
連接數(shù)據(jù)庫
import pymongo client = pymongo.MongoClient() db = client["database_name"] # 跟上數(shù)據(jù)庫名 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ù)庫及集合 self.client = pymongo.MongoClient() # 連接數(shù)據(jù)庫使用 self.db = self.client[database] # 指定使用的數(shù)據(jù)庫 self.col = self.db[collection] # 指定使用的集合 def insert(self, data, onlyOne=True): # onlyOne用來控制插入單條還是多條數(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ù)庫對大小寫敏感
MySQL
安裝模塊pip install pymysql
連接數(shù)據(jù)庫
import pymysql # 連接mysql db_config = { "host": "127.0.0.1", "port": 3306, "user": "admin", "password": "qwe123", "db": "stu", # 指定操作的數(shù)據(jù)庫 "charset": "utf8" } conn = pymysql.connect(**db_config) # mysql登錄 **是字典拆包 print(conn)
執(zhí)行操作
cur = conn.cursor() # 返回一個(gè)執(zhí)行數(shù)據(jù)庫命令游標(biāo)對象,通過游標(biāo)對象執(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)對象 conn.close() # 關(guān)閉數(shù)據(jù)庫
查詢數(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)對象 conn.close() # 關(guān)閉數(shù)據(jù)庫
Redis
安裝模塊pip install redis
連接數(shù)據(jù)庫
import redis # 登錄數(shù)據(jù)庫 # host ip地址 # decode_responses get獲得鍵值時(shí) True返回字符串?dāng)?shù)據(jù),默認(rèn)是False二進(jìn)制數(shù)據(jù) # db 指定數(shù)據(jù)庫,默認(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ù)庫的方法是red.[輸入redis數(shù)據(jù)庫操作命令]()
到此這篇關(guān)于Python與數(shù)據(jù)庫的交互的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)庫交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python中高效的json對比庫deepdiff詳解
- python處理json文件的四個(gè)常用函數(shù)
- 使用python如何提取JSON數(shù)據(jù)指定內(nèi)容
- python如何讀取和存儲(chǔ)dict()與.json格式文件
- 利用python實(shí)現(xiàn)JSON文檔與Python對象互相轉(zhuǎn)換
- python+html實(shí)現(xiàn)前后端數(shù)據(jù)交互界面顯示的全過程
- python tkinter與Mysql數(shù)據(jù)庫交互實(shí)現(xiàn)賬號登陸
- python實(shí)現(xiàn)與Oracle數(shù)據(jù)庫交互操作示例
- python 如何用urllib與服務(wù)端交互(發(fā)送和接收數(shù)據(jù))
- python GUI庫圖形界面開發(fā)之PyQt5中QWebEngineView內(nèi)嵌網(wǎng)頁與Python的數(shù)據(jù)交互傳參詳細(xì)方法實(shí)例
- python與json數(shù)據(jù)的交互詳情
相關(guān)文章
解決Python中的modf()函數(shù)取小數(shù)部分不準(zhǔn)確問題
這篇文章主要介紹了解決Python中的modf()函數(shù)取小數(shù)部分不準(zhǔn)確問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05python GUI庫圖形界面開發(fā)之PyQt5窗口布局控件QStackedWidget詳細(xì)使用方法
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5窗口布局控件QStackedWidget詳細(xì)使用方法,需要的朋友可以參考下2020-02-02Python supervisor強(qiáng)大的進(jìn)程管理工具的使用
這篇文章主要介紹了Python supervisor強(qiáng)大的進(jìn)程管理工具的使用,本文主要跟大家分享在類unix操作系統(tǒng)下supervisor的使用以及一些關(guān)于進(jìn)程的知識(shí),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04Pycharm2017版本設(shè)置啟動(dòng)時(shí)默認(rèn)自動(dòng)打開項(xiàng)目的方法
今天小編就為大家分享一篇Pycharm2017版本設(shè)置啟動(dòng)時(shí)默認(rèn)自動(dòng)打開項(xiàng)目的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10Python數(shù)據(jù)分析基礎(chǔ)之異常值檢測和處理方式
這篇文章主要介紹了Python數(shù)據(jù)分析基礎(chǔ)之異常值檢測和處理方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07Python之random.sample()和numpy.random.choice()的優(yōu)缺點(diǎn)說明
這篇文章主要介紹了Python之random.sample()和numpy.random.choice()的優(yōu)缺點(diǎn)說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06