簡(jiǎn)單的Lua 連接操作mysql數(shù)據(jù)庫(kù)的方法
發(fā)布日期:2022-01-31 00:49 | 文章來(lái)源:腳本之家
win 需要先安裝luaforwindows
linux 需要安裝 luarocks 并 luarocks install luasql-mysql
require"luasql.mysql"
--創(chuàng)建環(huán)境對(duì)象
env=luasql.mysql()
--連接數(shù)據(jù)庫(kù)
conn=env:connect("數(shù)據(jù)庫(kù)名","用戶名","密碼","IP地址",端口)
--設(shè)置數(shù)據(jù)庫(kù)的編碼格式
conn:execute"SET NAMES GB2312"
--執(zhí)行數(shù)據(jù)庫(kù)操作
cur=conn:execute("select * from role")
row=cur:fetch({},"a")
while row do
var=string.format("%d%s\n",row.id,row.name)
print(var)
row=cur:fetch(row,"a")
end
conn:close()--關(guān)閉數(shù)據(jù)庫(kù)連接
env:close()--關(guān)閉數(shù)據(jù)庫(kù)環(huán)境
上面是個(gè)簡(jiǎn)單的,我們?cè)賮?lái)看個(gè)稍微復(fù)雜些的例子
-- load driver
require "luasql.mysql"
-- create environment object
env = assert (luasql.mysql())
-- connect to data source
con = assert (env:connect("database", "usr", "password", "192.168.xx.xxx", 3306))
-- reset our table
res = con:execute"DROP TABLE people" --建立新表people
res = assert (con:execute[[
CREATE TABLE people(
name varchar(50),
email varchar(50)
)
]])
-- add a few elements
list = {
{ name="Jose das Couves", email="jose@couves.com", },
{ name="Manoel Joaquim", email="manoel.joaquim@cafundo.com", },
{ name="Maria das Dores", email="maria@dores.com", },
}
for i, p in pairs (list) do --加入數(shù)據(jù)到people表
res = assert (con:execute(string.format([[
INSERT INTO people
VALUES ('%s', '%s')]], p.name, p.email)
))
end
-- retrieve a cursor
cur = assert (con:execute"SELECT name, email from people") --獲取數(shù)據(jù)
-- print all rows
row = cur:fetch ({}, "a") -- the rows will be indexed by field names --顯示出來(lái)
while row do
print(string.format("Name: %s, E-mail: %s", row.name, row.email))
row = cur:fetch (row, "a") -- reusing the table of results
end
-- close everything
cur:close()
con:close()
env:close()
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章
上一篇:
關(guān)注官方微信