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)境
-- 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()