SAE Tornado 應用鏈接並使用 Mysql

今天由於要提供幾個開放的接口給我畢設相關的平臺調用,因此又開始折騰以前在SAE上搭的Tornado應用。html

以前記錄過一個 如何在 SAE 上使用 Tornado,此次續上,關於在SAE裏使用Tornado框架時基本的MySQL操做。由於本身剛纔找了好久資料才用起來,也怪本身以前沒在Tornado裏面用過MySQL,因此爲其餘同窗之後少走彎路來一個整理貼。python


首先在應用控制檯初始化共享型MySQLmysql

  • 點擊管理MySQL能夠進入管理後臺,標準的PHPMyAdminweb

根據 SAE官方文檔 底部介紹,你能夠經過如下方法得到鏈接數據庫所需的參數。sql

import sae.const

sae.const.MYSQL_DB      # 數據庫名
sae.const.MYSQL_USER    # 用戶名
sae.const.MYSQL_PASS    # 密碼
sae.const.MYSQL_HOST    # 主庫域名(可讀寫)
sae.const.MYSQL_PORT    # 端口,類型爲<type 'str'>,請根據框架要求自行轉換爲int
sae.const.MYSQL_HOST_S  # 從庫域名(只讀)

注意:須要將sae.const.MYSQL_PORT轉成int型數據庫

SAE Python內置了MySQLdb模塊,用法以下:框架

1 導入sae常量和MySQLdb模塊:tornado

import sae.const
import MySQLdb

2 鏈接數據庫:fetch

db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT ),user=sae.const.MYSQL_USER ,passwd=sae.const.MYSQL_PASS ,db=sae.const.MYSQL_DB)

3 獲取cursor對象,用於執行命令:.net

cursor = db.cursor() #默認類型,返回結果如:(u'ccc', 33L)
cursor = db.cursor(cursorclass=MySQLdb.cursors.DictCursor) #返回字典形式,如:{'name': u'ccc', 'created': 33L}

4 執行SQL語句:

cursor.execute(「select * from table_name where what = ‘what’」) #模擬數據: [{‘name’: ’chengkang’, ‘gender’: ‘male’},{‘name’: ’xiaoli’, ‘gender’: ’female’}]

5 輸出返回結果:

result = cursor.fetchone()
if result is None:
        print 「None」
else:
        print 「%s」%result #{‘name’: ’chengkang’, ‘gender’: ‘male’}
        print result[‘name’] #chengkang
        result = cursor.fetchall()
        for row in result:
                print 「%s」%row #{‘name’: ’chengkang’, ‘gender’: ‘male’}
                    for col in row:
                        print 「%s」%col #chengkangmale

以上是最基本的使用。反正我暫時就用到這些:)。一些細節的問題以後再來吧。

參考了這個博客


下面附上我本身試驗時候的代碼,可能會有一些參考價值。

class TestHandler(tornado.web.RequestHandler):
    def get(self):
        premise = self.get_argument('premise', "no_data")
        consequence = self.get_argument('consequence', "no_data")
        
        try:
            import sae.const
            import MySQLdb
            try:
                db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT ),user=sae.const.MYSQL_USER ,passwd=sae.const.MYSQL_PASS ,db=sae.const.MYSQL_DB)
                cursor = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
                #cursor = db.cursor()
                try:
                    cursor.execute("SELECT * FROM immediate_consequences")
                    one = cursor.fetchall()
                    #cursor.execute("SELECT * FROM immediate_consequences WHERE premise='"+premise+"' and consequence='"+consequence+"'")
                    #one = cursor.fetchone()
                    a = ""
                    #for row in cursor.fetchall():
                    #   for item in row:
                    #      a += item
                    if one is None:
                        self.write("Not in the database")
                    else:
                        #self.write(one['premise']+one['consequence'])
                        for item in one:
                            self.write("Yes%s"%item)
                    #self.write(a.fetchone())
                    #self.write("premise:",one['premise']," and consequence:",one['consequence'])
                except:
                    self.write(「wtf」)
                cursor.close()
            except:
                self.write("database connection error")
        except:
            self.write("Hello Tornado")

以上。

相關文章
相關標籤/搜索