本文實例講述了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()
新聞熱點
疑難解答