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