這次要為我的python程序加上數(shù)據(jù)庫,主要是實現(xiàn)從mysql中查詢出數(shù)據(jù)并在頁面上顯示出來。
首先是mysql的配置文件config.py
host="127.0.0.1" user="root" password="" charset="utf8" database="service" port=3306
然后是從數(shù)據(jù)庫中讀取數(shù)據(jù)的aService.py
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()返回是執(zhí)行語句影響的行數(shù),剛開始我以為是返回的結果,導致繞了很遠的彎路。真正為返回結果的是cursor.fechone(),表示獲取執(zhí)行結果的第一條。同時還有cursor.fetchall(),表示獲取所有結果。如果獲取了多個字段的話,結果為數(shù)組類型,按照查詢結果的字段順序排序。
MySQLdb是python與數(shù)據(jù)庫連接的一個模塊。這個模塊并不是本來就存在的,需要下載并安裝到python得目錄下才行。MAC安裝這個模塊有個奇怪的要求,就是必須在本機安裝了mysql,即便實際上程序使用的外部的數(shù)據(jù)庫。在已安裝mysql的前提下,發(fā)現(xiàn)安裝mysqldb錯誤,并報了mysql目錄找不到錯誤時,可用以下方法解決:
在用戶的home目錄下vi .profile
加入 export PATH=$PATH:/user/local/mysql/bin,退出并保存
再執(zhí)行source ./.profile命令并退出終端
這樣過后,在重新安裝mysqldb應該就不會報找不到mysql目錄的錯誤了。
接下來是主程序hello.py
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()
這個部分創(chuàng)建了一個訪問路徑/Service/A,該路徑對應的服務是hello類提供的。在這個類的get方法中調用了aService的getA方法。在頁面上顯示出一個json格式的文本。執(zhí)行步驟如下
終端:python hello.py 8080
瀏覽器:localhost:8080/Service/A
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
