Python操作MySQL數(shù)據(jù)庫(kù)的三種方法總結(jié)
1. MySQLdb 的使用
(1) 什么是MySQLdb?
MySQLdb 是用于 Python 連接 MySQL 數(shù)據(jù)庫(kù)的接口,它實(shí)現(xiàn)了 Python 數(shù)據(jù)庫(kù) API 規(guī)范 V2.0,基于 MySQL C API 上建立的。
(2) 源碼安裝 MySQLdb: https://pypi.python.org/pypi/MySQL-python
$ tar zxvf MySQL-python-*.tar.gz $ cd MySQL-python-* $ python setup.py build $ python setup.py install
(3) MySQLdb 的使用:
#!/usr/bin/env python # coding=utf-8 import MySQLdb def connectdb(): print('連接到mysql服務(wù)器...') # 打開(kāi)數(shù)據(jù)庫(kù)連接 # 用戶名:hp, 密碼:Hp12345.,用戶名和密碼需要改成你自己的mysql用戶名和密碼,并且要?jiǎng)?chuàng)建數(shù)據(jù)庫(kù)TESTDB,并在TESTDB數(shù)據(jù)庫(kù)中創(chuàng)建好表Student db = MySQLdb.connect("localhost","hp","Hp12345.","TESTDB") print('連接上了!') return db def createtable(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # 如果存在表Sutdent先刪除 cursor.execute("DROP TABLE IF EXISTS Student") sql = """CREATE TABLE Student ( ID CHAR(10) NOT NULL, Name CHAR(8), Grade INT )""" # 創(chuàng)建Sutdent表 cursor.execute(sql) def insertdb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 插入語(yǔ)句 sql = """INSERT INTO Student VALUES ('001', 'CZQ', 70), ('002', 'LHQ', 80), ('003', 'MQ', 90), ('004', 'WH', 80), ('005', 'HP', 70), ('006', 'YF', 66), ('007', 'TEST', 100)""" #sql = "INSERT INTO Student(ID, Name, Grade) \ # VALUES ('%s', '%s', '%d')" % \ # ('001', 'HP', 60) try: # 執(zhí)行sql語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: # Rollback in case there is any error print '插入數(shù)據(jù)失敗!' db.rollback() def querydb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 查詢語(yǔ)句 #sql = "SELECT * FROM Student \ # WHERE Grade > '%d'" % (80) sql = "SELECT * FROM Student" try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 獲取所有記錄列表 results = cursor.fetchall() for row in results: ID = row[0] Name = row[1] Grade = row[2] # 打印結(jié)果 print "ID: %s, Name: %s, Grade: %d" % \ (ID, Name, Grade) except: print "Error: unable to fecth data" def deletedb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 刪除語(yǔ)句 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100) try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 提交修改 db.commit() except: print '刪除數(shù)據(jù)失敗!' # 發(fā)生錯(cuò)誤時(shí)回滾 db.rollback() def updatedb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 更新語(yǔ)句 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003') try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: print '更新數(shù)據(jù)失敗!' # 發(fā)生錯(cuò)誤時(shí)回滾 db.rollback() def closedb(db): db.close() def main(): db = connectdb() # 連接MySQL數(shù)據(jù)庫(kù) createtable(db) # 創(chuàng)建表 insertdb(db) # 插入數(shù)據(jù) print '\n插入數(shù)據(jù)后:' querydb(db) deletedb(db) # 刪除數(shù)據(jù) print '\n刪除數(shù)據(jù)后:' querydb(db) updatedb(db) # 更新數(shù)據(jù) print '\n更新數(shù)據(jù)后:' querydb(db) closedb(db) # 關(guān)閉數(shù)據(jù)庫(kù) if __name__ == '__main__': main()
運(yùn)行結(jié)果:
2. PyMySQL 的使用
(1) 什么是 PyMySQL?
PyMySQL 是 Python 中用于連接 MySQL 服務(wù)器的一個(gè)庫(kù),它遵循 Python 數(shù)據(jù)庫(kù) API 規(guī)范 V2.0,并包含了 pure-Python MySQL 客戶端庫(kù)。
(2) 安裝 PyMysql:
pip install PyMysql
(3) 使用 PyMySQL:
#!/usr/bin/env python # coding=utf-8 import pymysql def connectdb(): print('連接到mysql服務(wù)器...') # 打開(kāi)數(shù)據(jù)庫(kù)連接 # 用戶名:hp, 密碼:Hp12345.,用戶名和密碼需要改成你自己的mysql用戶名和密碼,并且要?jiǎng)?chuàng)建數(shù)據(jù)庫(kù)TESTDB,并在TESTDB數(shù)據(jù)庫(kù)中創(chuàng)建好表Student db = pymysql.connect("localhost","hp","Hp12345.","TESTDB") print('連接上了!') return db def createtable(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # 如果存在表Sutdent先刪除 cursor.execute("DROP TABLE IF EXISTS Student") sql = """CREATE TABLE Student ( ID CHAR(10) NOT NULL, Name CHAR(8), Grade INT )""" # 創(chuàng)建Sutdent表 cursor.execute(sql) def insertdb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 插入語(yǔ)句 sql = """INSERT INTO Student VALUES ('001', 'CZQ', 70), ('002', 'LHQ', 80), ('003', 'MQ', 90), ('004', 'WH', 80), ('005', 'HP', 70), ('006', 'YF', 66), ('007', 'TEST', 100)""" #sql = "INSERT INTO Student(ID, Name, Grade) \ # VALUES ('%s', '%s', '%d')" % \ # ('001', 'HP', 60) try: # 執(zhí)行sql語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: # Rollback in case there is any error print '插入數(shù)據(jù)失敗!' db.rollback() def querydb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 查詢語(yǔ)句 #sql = "SELECT * FROM Student \ # WHERE Grade > '%d'" % (80) sql = "SELECT * FROM Student" try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 獲取所有記錄列表 results = cursor.fetchall() for row in results: ID = row[0] Name = row[1] Grade = row[2] # 打印結(jié)果 print "ID: %s, Name: %s, Grade: %d" % \ (ID, Name, Grade) except: print "Error: unable to fecth data" def deletedb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 刪除語(yǔ)句 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100) try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 提交修改 db.commit() except: print '刪除數(shù)據(jù)失敗!' # 發(fā)生錯(cuò)誤時(shí)回滾 db.rollback() def updatedb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 更新語(yǔ)句 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003') try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: print '更新數(shù)據(jù)失敗!' # 發(fā)生錯(cuò)誤時(shí)回滾 db.rollback() def closedb(db): db.close() def main(): db = connectdb() # 連接MySQL數(shù)據(jù)庫(kù) createtable(db) # 創(chuàng)建表 insertdb(db) # 插入數(shù)據(jù) print '\n插入數(shù)據(jù)后:' querydb(db) deletedb(db) # 刪除數(shù)據(jù) print '\n刪除數(shù)據(jù)后:' querydb(db) updatedb(db) # 更新數(shù)據(jù) print '\n更新數(shù)據(jù)后:' querydb(db) closedb(db) # 關(guān)閉數(shù)據(jù)庫(kù) if __name__ == '__main__': main()
運(yùn)行結(jié)果:
3. mysql.connector 的使用
(1) 什么是 mysql.connector?
由于 MySQL 服務(wù)器以獨(dú)立的進(jìn)程運(yùn)行,并通過(guò)網(wǎng)絡(luò)對(duì)外服務(wù),所以,需要支持 Python 的 MySQL 驅(qū)動(dòng)來(lái)連接到 MySQL 服務(wù)器。
目前,有兩個(gè) MySQL 驅(qū)動(dòng):
mysql-connector-python:是 MySQL 官方的純 Python 驅(qū)動(dòng);
MySQL-python :是封裝了 MySQL C驅(qū)動(dòng)的 Python 驅(qū)動(dòng)。
(2) 安裝 mysql.connector:
pip install mysql-connector-python pip install MySQL-python
(3) 使用 mysql.connector:
#!/usr/bin/env python # coding=utf-8 import mysql.connector def connectdb(): print('連接到mysql服務(wù)器...') # 打開(kāi)數(shù)據(jù)庫(kù)連接 # 用戶名:hp, 密碼:Hp12345.,用戶名和密碼需要改成你自己的mysql用戶名和密碼,并且要?jiǎng)?chuàng)建數(shù)據(jù)庫(kù)TESTDB,并在TESTDB數(shù)據(jù)庫(kù)中創(chuàng)建好表Student db = mysql.connector.connect(user="hp", passwd="Hp12345.", database="TESTDB", use_unicode=True) print('連接上了!') return db def createtable(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # 如果存在表Sutdent先刪除 cursor.execute("DROP TABLE IF EXISTS Student") sql = """CREATE TABLE Student ( ID CHAR(10) NOT NULL, Name CHAR(8), Grade INT )""" # 創(chuàng)建Sutdent表 cursor.execute(sql) def insertdb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 插入語(yǔ)句 sql = """INSERT INTO Student VALUES ('001', 'CZQ', 70), ('002', 'LHQ', 80), ('003', 'MQ', 90), ('004', 'WH', 80), ('005', 'HP', 70), ('006', 'YF', 66), ('007', 'TEST', 100)""" #sql = "INSERT INTO Student(ID, Name, Grade) \ # VALUES ('%s', '%s', '%d')" % \ # ('001', 'HP', 60) try: # 執(zhí)行sql語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: # Rollback in case there is any error print '插入數(shù)據(jù)失敗!' db.rollback() def querydb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 查詢語(yǔ)句 #sql = "SELECT * FROM Student \ # WHERE Grade > '%d'" % (80) sql = "SELECT * FROM Student" try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 獲取所有記錄列表 results = cursor.fetchall() for row in results: ID = row[0] Name = row[1] Grade = row[2] # 打印結(jié)果 print "ID: %s, Name: %s, Grade: %d" % \ (ID, Name, Grade) except: print "Error: unable to fecth data" def deletedb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 刪除語(yǔ)句 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100) try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 提交修改 db.commit() except: print '刪除數(shù)據(jù)失敗!' # 發(fā)生錯(cuò)誤時(shí)回滾 db.rollback() def updatedb(db): # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 更新語(yǔ)句 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003') try: # 執(zhí)行SQL語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: print '更新數(shù)據(jù)失敗!' # 發(fā)生錯(cuò)誤時(shí)回滾 db.rollback() def closedb(db): db.close() def main(): db = connectdb() # 連接MySQL數(shù)據(jù)庫(kù) createtable(db) # 創(chuàng)建表 insertdb(db) # 插入數(shù)據(jù) print '\n插入數(shù)據(jù)后:' querydb(db) deletedb(db) # 刪除數(shù)據(jù) print '\n刪除數(shù)據(jù)后:' querydb(db) updatedb(db) # 更新數(shù)據(jù) print '\n更新數(shù)據(jù)后:' querydb(db) closedb(db) # 關(guān)閉數(shù)據(jù)庫(kù) if __name__ == '__main__': main()
運(yùn)行結(jié)果:
以上這篇Python操作MySQL數(shù)據(jù)庫(kù)的三種方法總結(jié)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
pandas實(shí)現(xiàn)excel表格處理并讀取指定sheet的方法
這篇文章主要介紹了pandas實(shí)現(xiàn)excel表格處理并讀取指定sheet的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02python實(shí)現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr
這篇文章主要介紹了python實(shí)現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03Python中的pathlib.Path為什么不繼承str詳解
這篇文章主要給大家介紹了關(guān)于Python中pathlib.Path為什么不繼承str的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06檢測(cè)tensorflow是否使用gpu進(jìn)行計(jì)算的方式
今天小編就為大家分享一篇檢測(cè)tensorflow是否使用gpu進(jìn)行計(jì)算的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02僅用50行代碼實(shí)現(xiàn)一個(gè)Python編寫(xiě)的計(jì)算器的教程
這篇文章主要介紹了僅用50行代碼實(shí)現(xiàn)一個(gè)Python編寫(xiě)的計(jì)算器的教程,主要用到了PlyPlus庫(kù)使得核心代碼十分簡(jiǎn)單,需要的朋友可以參考下2015-04-04Python實(shí)現(xiàn)視頻畫(huà)質(zhì)增強(qiáng)的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Python語(yǔ)言實(shí)現(xiàn)對(duì)視頻進(jìn)行畫(huà)質(zhì)增強(qiáng)功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以嘗試一下2022-04-04python輸出國(guó)際象棋棋盤(pán)的實(shí)例分享
在本篇文章里小編給大家整理的是一篇關(guān)于python輸出國(guó)際象棋棋盤(pán)的實(shí)例詳解,有興趣的朋友們可以參考下。2020-11-11Python根據(jù)字符串調(diào)用函數(shù)過(guò)程解析
這篇文章主要介紹了Python根據(jù)字符串調(diào)用函數(shù)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11python基礎(chǔ)學(xué)習(xí)之生成器與文件系統(tǒng)知識(shí)總結(jié)
本文是參考《python數(shù)據(jù)分析》的附錄對(duì)生成器和文件系統(tǒng)結(jié)合案例的一個(gè)簡(jiǎn)單回顧,文中對(duì)python生成器與文件系統(tǒng)作了非常詳細(xì)的介紹,對(duì)正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05