lua+mysql 操作DB

结果如下:

http://db.enjoy.com/mysql

 

做法:

local mysql = require "resty.mysql"
local cjson = require "cjson"

--配置
local config = {
    host = "192.168.99.45",
    port = 3306,
    database = "tinggood_caiji",
    user = "root",
    password = "123456"
}

--打开连接
local function open_mysql()
    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

--关闭连接
local 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

local db = open_mysql()
local sql = "select * from account "
--设置中文编码
ngx.header['Content-Type']="text/html;charset=UTF-8"

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

--json方式输出
ngx.say(cjson.encode(res))
 

server {
  listen  80;
  server_name  db.enjoy.com;


   location ^~ /mysql {
      content_by_lua_file /etc/nginx/lua/mysql_sel.lua;
   }


}
 

 

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页