Python訪問MySQL封裝的常用類執行個體

來源:互聯網
上載者:User
本文執行個體講述了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程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.