讓我們來做個django小專案之二
上篇內容我們算是來了一個開場,建立了我們的專案,最後把資料庫也建立完成了,這篇我們主要完成後臺數據入庫的部分,根據我們之前的思路,如果已經能實時獲得每個站點效能資訊了,如果能將每次獲得資訊插入到資料庫中,這個就完成了我們的入庫部分,這裡說一下我們的資料庫操作部分,要操作資料庫,首先我們要跟資料庫建立連線,然後進行常規的CRUD操作,操作完畢後再關閉資料庫連線,這是一個基本流程,所以為了提高資料庫的操作速度,我們可以把一些常用的操作封裝成一個類,以下是我門資料庫操作的類程式碼:
class database: def __init__(self, dbname=None, dbhost=None): self._logger = logger 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._dbport = int(DBPORT) self._conn = self.connectSQL/">MySQL() 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) 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 self._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 self._logger.warn("update database exception, %s" % data) 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: self._logger.warn("close database exception, %s,%s,%s" % (data, type(self._cursor), type(self._conn)))
在這個類中我們先定義了__init__方法,指定了資料庫連線,使用者,埠,使用者等資訊,接下來是定義了三個方法,分別是建立資料庫連線,獲取資料內容、更新資料庫及最後關閉資料庫連線,正題邏輯就是這樣,程式碼沒特別內容。