這次要為我的python程式加上資料庫,主要是實現從mysql中查詢出資料並在頁面上顯示出來。
首先是mysql的設定檔config.py
host="127.0.0.1"user="root"password=""charset="utf8"database="service"port=3306
然後是從資料庫中讀取資料的aService.py
import MySQLdbimport sysimport configclass AService(object): def getA(self,id): conn = MySQLdb.connect(host=config.host,user=config.user,passwd=config.password,port=config.port,db=config.database,charset=config.charset) result=[] try: cursor = conn.cursor(); cursor.execute("select id,code,title from test_a where id='%d'"%(id)) result = cursor.fetchone() except Exception,e: print "System error: ",e result = "error" finally: cursor.close() conn.close() return result
其中cursor.execute()返回是執行語句影響的行數,剛開始我以為是返回的結果,導致繞了很遠的彎路。真正為返回結果的是cursor.fechone(),表示擷取執行結果的第一條。同時還有cursor.fetchall(),表示擷取所有結果。如果擷取了多個欄位的話,結果為數群組類型,按照查詢結果的欄位順序排序。
MySQLdb是python與資料庫連接的一個模組。這個模組並不是本來就存在的,需要下載並安裝到python得目錄下才行。MAC安裝這個模組有個奇怪的要求,就是必須在本機安裝了mysql,即便實際上程式使用的外部的資料庫。在已安裝mysql的前提下,發現安裝mysqldb錯誤,並報了mysql目錄找不到錯誤時,可用以下方法解決:
在使用者的home目錄下vi .profile
加入 export PATH=$PATH:/user/local/mysql/bin,退出並儲存
再執行source ./.profile命令並退出終端
這樣過後,在重新安裝mysqldb應該就不會報找不到mysql目錄的錯誤了。
接下來是主程式hello.py
import webimport aServiceimport sys urls = ("/Service/A","hello")app = web.application(urls,globals()) class hello: def GET(self): mservice = aService.AService() result = mservice.getA(1) json = "" json +="{" json +="'id':"+str(result[0])+"," json +="'code':'"+result[1]+"'," json +="'title':'"+result[2]+"'" json +="}" return json;if __name__=="__main__": app.run()
這個部分建立了一個訪問路徑/Service/A,該路徑對應的服務是hello類提供的。在這個類的get方法中調用了aService的getA方法。在頁面上顯示出一個json格式的文本。執行步驟如下
終端:python hello.py 8080
瀏覽器:localhost:8080/Service/A