1. 程式人生 > >python封裝資料庫

python封裝資料庫

#db.conf
#配置資料庫
[database]
dbhost=127.0.0.1
dbport=3366
dbname=test
dbuser=test
dbpassword=test
dbcharset=utf8

2.讀取配置

import ConfigParser
import os

#獲取config配置檔案
def getConfig(section, key):
    config = ConfigParser.ConfigParser()
    path = os.path.split(os.path.realpath(__file__))[0] + '\db.conf'
# linux / config.read(path) return config.get(section, key)

3.連結資料庫

# encoding:utf-8
# name:mod_db.py
'''
使用方法:1.在主程式中先例項化DB Mysql資料庫操作類。
      2.使用方法:db=database()  db.fetch_all("sql")
'''
import MySQLdb
import MySQLdb.cursors
import mod_config
import mod_logger

DB = "database"
LOGPATH = mod_config.getConfig('path'
, 'logpath') + 'database.log' DBNAME = mod_config.getConfig(DB, 'dbname') DBHOST = mod_config.getConfig(DB, 'dbhost') DBUSER = mod_config.getConfig(DB, 'dbuser') DBPWD = mod_config.getConfig(DB, 'dbpassword') DBCHARSET = mod_config.getConfig(DB, 'dbcharset') DBPORT = mod_config.getConfig(DB, "dbport"
) logger = mod_logger # 資料庫操作類 class database: # 注,python的self等於其它語言的this def __init__(self, dbname=None, dbhost=None): self._logger = logger # 這裡的None相當於其它語言的NULL if dbname is None: self._dbname = DBNAME else: self._dbname = dbname if dbhost is None: self._dbhost = DBHOST else: self._dbhost = dbhost self._dbuser = DBUSER self._dbpassword = DBPWD self._dbcharset = DBCHARSET self._dbport = int(DBPORT) self._conn = self.connectMySQL() if (self._conn): self._cursor = self._conn.cursor() # 資料庫連線 def connectMySQL(self): conn = False try: conn = MySQLdb.connect(host=self._dbhost, user=self._dbuser, passwd=self._dbpassword, db=self._dbname, port=self._dbport, cursorclass=MySQLdb.cursors.DictCursor, charset=self._dbcharset, ) cursor = conn.cursor() except Exception, data: self._logger.error("connect database failed, %s" % data) conn = False return conn # 獲取查詢結果集 def fetch_all(self, sql): res = '' if (self._conn): try: self._cursor.execute(sql) res = self._cursor.fetchall() except Exception, data: res = False logger.warn("query database exception, %s" % data) return res def update(self, sql): flag = False if (self._conn): try: self._cursor.execute(sql) self._conn.commit() flag = True except Exception, data: flag = False logger.warn("update database exception, %s" % data) return flag #更新資料庫中表的某幾列:update login set result =%s;eg:sql='insert into pythontest values(%s,%s,%s,now()',params=(6,'C#','good book') def updateByParams(self, sql, params): flag = False if (self._conn): try: self._cursor.execute(sql,params) self._conn.commit() flag = True except mdb.Error as data: flag = False logger.warn("update database by params exception, %s" % data) finally: self.close() return flag # 關閉資料庫連線 def close(self): if (self._conn): try: if (type(self._cursor) == 'object'): self._cursor.close() if (type(self._conn) == 'object'): self._conn.close() except Exception, data: logger.warn("close database exception, %s,%s,%s" % (data, type(self._cursor), type(self._conn)))