[openresty]第二节:操作mysql数据库

openresty操作数据库本质上调用了lua-resty-mysql 组件

具体参照git:https://github.com/openresty/lua-resty-mysql#table-of-contents

同样的在/usr/local/openresty/work/conf/ 文件夹下添加新的文件mysql.conf

内容如下:


worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
server {
listen 8089;
server_name localhost;
location / {
content_by_lua '
local arg = ngx.req.get_uri_args()
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) -- 1 sec
local ok, err, errcode, sqlstate = db:connect{
host = "127.0.0.1",
port = 3306,
database = "test",
user = "xxxx",
password = "xxxxxxx",
max_packet_size = 1024 * 1024 }

if not ok then
ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)
return
end

--ngx.say("connected to mysql.")
local id = tonumber(arg.id)
queryStr = "select goods_id,goods_name from goods_test where goods_id ="..id
--ngx.say(queryStr)
res, err, errcode, sqlstate =
--db:query("select * from goods_test order by goods_id asc", 10)
db:query(queryStr)
if not res then
ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
return
end
local cjson = require "cjson"
ngx.say("result: ", cjson.encode(res))
';
}

}
}

是不是很简单,然后../nginx/sbin/nginx -p `pwd`/ -s reload -c conf/mysql.conf

重新加载配置文件,这样访问localhost:8089?id=1 就可以筛选数据库中主键ID=1的数据了。应该有mysql注入问题,所以参数全部转化为int类型,基本的网络安全意识不能没有。

 

发表评论

邮箱地址不会被公开。 必填项已用*标注


*