操作mysql主要用到了lua-resty-mysql庫,代碼可以在github上找得到
而且上面也有實例代碼
由於官網給出的例子比較基本,代碼也比較多,所以我這里主要介紹一些怎么封裝一下,簡化我們調用的代碼
lua/mysql.lua
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自動使用連接池
lua/hello.lua
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 command = ("insert into ip_access (`ip`) values ('" .. val .. "')");
local select = ("select * from ip_access where status = 1 and ip = ('" .. addr_ip .. "')");
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?name=root
即可獲取mysql中的name為root的的所有用戶,如果沒有name參數,則默認獲取root的值
從輸出的數據中,可以看出res其實是一個數組,而且不管返回的數據是多少條,它都是一個數組,當我們查詢的結果只有一條的時候,可以通過 res[1] 來獲取一條記錄,每一行數據又是一個table,可以通過列名來得到value
ok,到這里我們已經可以獲取用戶輸入的值,並且從mysql中獲取數據,然后返回json數據了,已經可以開發一些簡單的接口了
示例代碼 參見demo5部分
