此次要爲個人python程序加上數據庫,主要是實現從mysql中查詢出數據並在頁面上顯示出來。
python
首先是mysql的配置文件config.pymysql
host="127.0.0.1" user="root" password="" charset="utf8" database="service" port=3306
而後是從數據庫中讀取數據的aService.pyweb
import MySQLdb import sys import config class 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(),表示獲取全部結果。若是獲取了多個字段的話,結果爲數組類型,按照查詢結果的字段順序排序。sql
MySQLdb是python與數據庫鏈接的一個模塊。這個模塊並非原本就存在的,須要下載並安裝到python得目錄下才行。MAC安裝這個模塊有個奇怪的要求,就是必須在本機安裝了mysql,即使實際上程序使用的外部的數據庫。在已安裝mysql的前提下,發現安裝mysqldb錯誤,並報了mysql目錄找不到錯誤時,可用如下方法解決:數據庫
在用戶的home目錄下vi .profilejson
加入 export PATH=$PATH:/user/local/mysql/bin,退出並保存數組
再執行source ./.profile命令並退出終端瀏覽器
這樣事後,在從新安裝mysqldb應該就不會報找不到mysql目錄的錯誤了。app
接下來是主程序hello.pyfetch
import web import aService import 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