簡單的Lua 連接操作mysql數(shù)據(jù)庫的方法
更新時間:2015年10月12日 08:49:22 投稿:hebedich
lua連接數(shù)據(jù)庫不只luasql這個庫,但目前更新最快的的貌似是這個luasql,他是開源的,下面我們就來看看如何來具體操作吧
win 需要先安裝luaforwindows
linux 需要安裝 luarocks 并 luarocks install luasql-mysql
require"luasql.mysql"
--創(chuàng)建環(huán)境對象
env=luasql.mysql()
--連接數(shù)據(jù)庫
conn=env:connect("數(shù)據(jù)庫名","用戶名","密碼","IP地址",端口)
--設(shè)置數(shù)據(jù)庫的編碼格式
conn:execute"SET NAMES GB2312"
--執(zhí)行數(shù)據(jù)庫操作
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ù)庫連接
env:close()--關(guān)閉數(shù)據(jù)庫環(huán)境
上面是個簡單的,我們再來看個稍微復(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 --顯示出來
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()
您可能感興趣的文章:
相關(guān)文章
Lua獲取網(wǎng)絡(luò)時間(獲取時間同步服務(wù)器的時間)
這篇文章主要介紹了Lua獲取網(wǎng)絡(luò)時間(獲取時間同步服務(wù)器的時間),本文使用Lua作為客戶端獲取網(wǎng)絡(luò)上的一些授時服務(wù)提供商的時間,需要的朋友可以參考下2015-04-04
C++中調(diào)用Lua配置文件和響應(yīng)函數(shù)示例
這篇文章主要介紹了C++中調(diào)用Lua配置文件和響應(yīng)函數(shù)示例,本文使用Lua文件作為配置文件,并寫了幾個響應(yīng)函數(shù)以便在C++中使用,需要的朋友可以參考下
2015-07-07 
