Lua 資料庫訪問
本文主要為大家介紹 Lua 資料庫的操作庫:LuaSQL。他是開源的,支持的資料庫有:ODBC, ADO, Oracle, MySQL, SQLite 和 PostgreSQL。
本文為大家介紹MySQL的資料庫連接。
LuaSQL 可以使用 LuaRocks 來安裝可以根據需要安裝你需要的資料庫驅動。
LuaRocks 安裝方法:
$ wget http://luarocks.org/releases/luarocks-2.2.1.tar.gz
$ tar zxpf luarocks-2.2.1.tar.gz
$ cd luarocks-2.2.1
$ ./configure; sudo make bootstrap
$ sudo luarocks install luasocket
$ lua
Lua 5.3.0 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> require "socket"
$ tar zxpf luarocks-2.2.1.tar.gz
$ cd luarocks-2.2.1
$ ./configure; sudo make bootstrap
$ sudo luarocks install luasocket
$ lua
Lua 5.3.0 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> require "socket"
Window 下安裝 LuaRocks:https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows
安裝不同資料庫驅動:
luarocks install luasql-sqlite3
luarocks install luasql-postgres
luarocks install luasql-mysql
luarocks install luasql-sqlite
luarocks install luasql-odbc
luarocks install luasql-postgres
luarocks install luasql-mysql
luarocks install luasql-sqlite
luarocks install luasql-odbc
你也可以使用源碼安裝方式,Lua Github 源碼地址:https://github.com/keplerproject/luasql
Lua 連接MySql 資料庫:
實例
require "luasql.mysql"
--創建環境對象
env = luasql.mysql()
--連接資料庫
conn = env:connect("資料庫名","用戶名","密碼","IP地址",端口)
--設置資料庫的編碼格式
conn:execute"SET NAMES UTF8"
--執行數據庫操作
cur = conn:execute("select * from role")
row = cur:fetch({},"a")
--檔對象的創建
file = io.open("role.txt","w+");
while row do
var = string.format("%d %s\n", row.id, row.name)
print(var)
file:write(var)
row = cur:fetch(row,"a")
end
file:close() --關閉檔對象
conn:close() --關閉資料庫連接
env:close() --關閉資料庫環境
--創建環境對象
env = luasql.mysql()
--連接資料庫
conn = env:connect("資料庫名","用戶名","密碼","IP地址",端口)
--設置資料庫的編碼格式
conn:execute"SET NAMES UTF8"
--執行數據庫操作
cur = conn:execute("select * from role")
row = cur:fetch({},"a")
--檔對象的創建
file = io.open("role.txt","w+");
while row do
var = string.format("%d %s\n", row.id, row.name)
print(var)
file:write(var)
row = cur:fetch(row,"a")
end
file:close() --關閉檔對象
conn:close() --關閉資料庫連接
env:close() --關閉資料庫環境