Lua Database Access
This article primarily introduces the Lua database operation library: LuaSQL. It is open-source and supports databases such as ODBC, ADO, Oracle, MySQL, SQLite, and PostgreSQL.
This article will guide you through connecting to a MySQL database.
LuaSQL can be installed using LuaRocks, where you can install the necessary database drivers as needed.
LuaRocks installation method:
$ 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"
LuaRocks installation on Windows: https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows
Installing different database drivers:
luarocks install luasql-sqlite3
luarocks install luasql-postgres
luarocks install luasql-mysql
luarocks install luasql-sqlite
luarocks install luasql-odbc
You can also install from source, Lua GitHub source address: https://github.com/keplerproject/luasql
Connecting to a MySQL database in Lua:
Example
require "luasql.mysql"
-- Create environment object
env = luasql.mysql()
-- Connect to database
conn = env:connect("database_name","username","password","IP_address",port)
-- Set database encoding format
conn:execute"SET NAMES UTF8"
-- Execute database operations
cur = conn:execute("select * from role")
row = cur:fetch({},"a")
-- Create file object
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() -- Close file object
conn:close() -- Close database connection
env:close() -- Close database environment