本文執行個體講述了Python訪問MySQL封裝的常用類。分享給大家供大家參考。具體如下:
python訪問mysql比較簡單,下面整理的就是一個很簡單的Python訪問MySQL資料庫類。
自己平時也就用到兩個mysql函數:查詢和更新,下面是自己常用的函數的封裝,大家拷貝過去直接可以使用。
檔案名稱:DBUtil.py
複製代碼 代碼如下:
# -*- encoding:utf8 -*-
'''
@author: crazyant.net
@version: 2013-10-22
封裝的mysql常用函數
'''
import MySQLdb
class DB():
def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PWD, DB_NAME):
self.DB_HOST = DB_HOST
self.DB_PORT = DB_PORT
self.DB_USER = DB_USER
self.DB_PWD = DB_PWD
self.DB_NAME = DB_NAME
self.conn = self.getConnection()
def getConnection(self):
return MySQLdb.Connect(
host=self.DB_HOST, #設定MYSQL地址
port=self.DB_PORT, #設定連接埠號碼
user=self.DB_USER, #設定使用者名稱
passwd=self.DB_PWD, #設定密碼
db=self.DB_NAME, #資料庫名
charset='utf8' #設定編碼
)
def query(self, sqlString):
cursor=self.conn.cursor()
cursor.execute(sqlString)
returnData=cursor.fetchall()
cursor.close()
self.conn.close()
return returnData
def update(self, sqlString):
cursor=self.conn.cursor()
cursor.execute(sqlString)
self.conn.commit()
cursor.close()
self.conn.close()
if __name__=="__main__":
db=DB('127.0.0.1',3306,'root','','wordpress')
print db.query("show tables;")
使用方法為檔案下面的main函數,使用query執行select語句並擷取結果;或者使用update進行insert、delete等操作。
希望本文所述對大家的Python程式設計有所協助。