Python所有的數(shù)據(jù)庫接口程序都在一定程度上遵守 Python DB-API 規(guī)范。
DB-API定義了一系列必須的對象和數(shù)據(jù)庫存取方式,以便為各種底層數(shù)據(jù)庫系統(tǒng)和多種多樣的數(shù)據(jù)庫接口程序提供一致的訪問接口。由于DB-API 為不同的數(shù)據(jù)庫提供了一致的訪問接口, 在不同的數(shù)據(jù)庫之間移植代碼成為一件輕松的事情。
在Python中如果要連接數(shù)據(jù)庫,不管是MySQL、SQL Server、PostgreSQL亦或是SQLite,使用時都是采用游標(biāo)的方式。
$ pip3 install PyMySQL
創(chuàng)建連接
import pymysql # 創(chuàng)建連接方式1 db = pymysql.connect(host='localhost', user='root', password='root', db='test', port=3306) # 創(chuàng)建連接方式2 db = pymysql.connect(dsn='localhost:test', user='root', password='root')
close()
關(guān)閉此connect對象, 關(guān)閉后無法再進(jìn)行操作,除非再次創(chuàng)建連接。
cursor()
創(chuàng)建游標(biāo)對象。一個游標(biāo)允許用戶執(zhí)行數(shù)據(jù)庫命令和得到查詢結(jié)果。一個 Python DB-API 游標(biāo)對象總是扮演游標(biāo)的角色, 無論數(shù)據(jù)庫是否真正支持游標(biāo)。也就說,數(shù)據(jù)庫接口程序必須實(shí)現(xiàn)游標(biāo)對象。創(chuàng)建游標(biāo)對象之后, 你就可以執(zhí)行查詢或其它命令(或者多個查詢和多個命令), 也可以從結(jié)果集中取出一條或多條記錄。
commit()
提交當(dāng)前事務(wù),執(zhí)行游標(biāo)對象的所有更新操作。
rollback()
取消當(dāng)前事務(wù),回滾當(dāng)前游標(biāo)的所有操作。
游標(biāo)操作
cursor = db.cursor()
查詢操作
import pymysql db = pymysql.connect(host='localhost', user='root', password='root', db='test') cursor = db.cursor() sql = '''select * from t_account''' try: cursor.execute(sql) # 方式1讀取結(jié)果集 rows = cursor.fetchall() for row in rows: print(row) # 方式2讀取結(jié)果集 for i in range(cursor.rowcount): result = cursor.fetchone() print(result) except Exception as e: raise e finally: cursor.close() db.close()
添加操作
import pymysql db = pymysql.connect(host='localhost', user='root', password='root', db='test') cursor = db.cursor() sql = '''insert into t_account values(default,'zhangsan','z',100,'張三')''' try: print(cursor.execute(sql)) db.commit() except: db.rollback() finally: cursor.close() db.close()
修改操作
import pymysql db = pymysql.connect(host='localhost', user='root', password='root', db='test') cursor = db.cursor() sql = '''update t_account set realname = '李四' where id = '5' ''' try: print(cursor.execute(sql)) db.commit() except: db.rollback() finally: cursor.close() db.close()
刪除操作
import pymysql db = pymysql.connect(host='localhost', user='root', password='root', db='test') cursor = db.cursor() sql = '''delete from t_account where id = '5' ''' try: print(cursor.execute(sql)) db.commit() except: db.rollback() finally: cursor.close() db.close()
調(diào)用存儲過程
cursor.callproc("存儲過程名稱") for result in cursor.fetchall(): print(result)
到此這篇關(guān)于教你怎么用Python操作MySql數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Python操作MySql內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:酒泉 金融催收 寧夏 云南 定西 龍巖 江蘇 商丘
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《教你怎么用Python操作MySql數(shù)據(jù)庫》,本文關(guān)鍵詞 教你,怎么,用,Python,操作,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。