简单的Lua 连接操作mysql数据库的方法
win需要先安装luaforwindows
linux需要安装luarocks并luarocksinstallluasql-mysql
require"luasql.mysql"
--创建环境对象
env=luasql.mysql()
--连接数据库
conn=env:connect("数据库名","用户名","密码","IP地址",端口)
--设置数据库的编码格式
conn:execute"SETNAMESGB2312"
--执行数据库操作
cur=conn:execute("select*fromrole")
row=cur:fetch({},"a")
whilerowdo
var=string.format("%d%s\n",row.id,row.name)
print(var)
row=cur:fetch(row,"a")
end
conn:close()--关闭数据库连接
env:close()--关闭数据库环境
上面是个简单的,我们再来看个稍微复杂些的例子
--loaddriver
require"luasql.mysql"
--createenvironmentobject
env=assert(luasql.mysql())
--connecttodatasource
con=assert(env:connect("database","usr","password","192.168.xx.xxx",3306))
--resetourtable
res=con:execute"DROPTABLEpeople"--建立新表people
res=assert(con:execute[[
CREATETABLEpeople(
namevarchar(50),
emailvarchar(50)
)
]])
--addafewelements
list={
{name="JosedasCouves",email="jose@couves.com",},
{name="ManoelJoaquim",email="manoel.joaquim@cafundo.com",},
{name="MariadasDores",email="maria@dores.com",},
}
fori,pinpairs(list)do--加入数据到people表
res=assert(con:execute(string.format([[
INSERTINTOpeople
VALUES('%s','%s')]],p.name,p.email)
))
end
--retrieveacursor
cur=assert(con:execute"SELECTname,emailfrompeople")--获取数据
--printallrows
row=cur:fetch({},"a")--therowswillbeindexedbyfieldnames--显示出来
whilerowdo
print(string.format("Name:%s,E-mail:%s",row.name,row.email))
row=cur:fetch(row,"a")--reusingthetableofresults
end
--closeeverything
cur:close()
con:close()
env:close()
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下