lua连接mysql

lua连接MYSQL,默认luajit没有mysql库,这里需要下载安装才能使用。

一、下载lua mysql库

git clone https://github.com/openresty/lua-resty-mysql.git

复制mysql.lua到luajit安装目录下的resty目录,

cp mysql.lua /usr/local/LuaJIT/share/luajit-2.0.5/resty

二、lua连接mysql

#nginx
location = /testscript{
     default_type text/plain;
     content_by_lua_file html/luafile/test.lua;
}

#test.lua
vim test.lua

local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
    ngx.say("failed to instantiate mysql: ", err) 
    return
end
db:set_timeout(1000)

local ok, err, errcode, sqlstate = db:connect{
    host = "127.0.0.1",
    port = 3306,
    database = "test",
    user = "root",
    password = "123456",
    charset = "utf8",
    max_packet_size = 1024 * 1024,                
}
if not ok then
    ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)
    return
end
ngx.say("connected to mysql.")

res, err, errcode, sqlstate = db:query("select、insert、update、delete ...sql语句")
if not res then
    ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
    return
end
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
1
粉丝
0
喜欢
0
收藏
0
排名:2920
访问:39
私信
所有博文