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部分

相关文章
相关标签/搜索