openresty 前端開發入門五之Mysql篇

openresty 前端開發入門五之Mysql篇前端

這章主要演示怎麼經過lua鏈接mysql,並根據用戶輸入的name從mysql獲取數據,並返回給用戶

操做mysql主要用到了lua-resty-mysql庫,代碼能夠在github上找獲得mysql

並且上面也有實例代碼git

因爲官網給出的例子比較基本,代碼也比較多,因此我這裏主要介紹一些怎麼封裝一下,簡化咱們調用的代碼github

lua/mysql.luaweb

local mysql = require "resty.mysql"

local config = {
    host = "localhost",
    port = 3306,
    database = "mysql",
    user = "root",
    password = "admin"
}

local _M = {}


function _M.new(self)
    local db, err = mysql:new()
    if not db then
        return nil
    end
    db:set_timeout(1000) -- 1 sec

    local ok, err, errno, sqlstate = db:connect(config)

    if not ok then
        return nil
    end
    db.close = close
    return db
end

function close(self)
    local sock = self.sock
    if not sock then
        return nil, "not initialized"
    end
    if self.subscribed then
        return nil, "subscribed state"
    end
    return sock:setkeepalive(10000, 50)
end

return _M

其實就是簡單把鏈接,跟關閉作一個簡單的封裝,隱藏繁瑣的初始化已經鏈接池細節,只須要調用new,就自動就連接了redis,close自動使用鏈接池redis

lua/hello.luasql

local cjson = require "cjson"
local mysql = require "mysql"
local req = require "req"

local args = req.getArgs()

local name = args['name']

if name == nil or name == "" then
    name = "root"    
end

name = ngx.quote_sql_str(name) -- SQL 轉義,將 ' 轉成 \', 防SQL注入,而且轉義後的變量包含了引號,因此能夠直接當成條件值使用

local db = mysql:new()

local sql = "select * from user where User = " .. name

ngx.say(sql)
ngx.say("<br/>")

local res, err, errno, sqlstate = db:query(sql)
db:close()
if not res then
    ngx.say(err)
    return {}
end

ngx.say(cjson.encode(res))

訪問
http://localhost/lua/hello?na...json

便可獲取mysql中的name爲root的的全部用戶,若是沒有name參數,則默認獲取root的值數組

從輸出的數據中,能夠看出res實際上是一個數組,並且無論返回的數據是多少條,它都是一個數組,當咱們查詢的結果只有一條的時候,能夠經過 res[1] 來獲取一條記錄,每一行數據又是一個table,能夠經過列名來獲得valueui

ok,到這裏咱們已經能夠獲取用戶輸入的值,而且從mysql中獲取數據,而後返回json數據了,已經能夠開發一些簡單的接口了

示例代碼 參見demo5部分

相關文章
相關標籤/搜索