Lua Database Access
This article mainly introduces the Lua database operation library:LuaSQLIt is open source, and the supported databases include: ODBC, ADO, Oracle, MySQL, SQLite and PostgreSQL.
This article introduces the MySQL database connection.
LuaSQL can be usedLuaRocksto install; you can install the database driver you need 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"
$ 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"
Installing LuaRocks 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
luarocks install luasql-postgres
luarocks install luasql-mysql
luarocks install luasql-sqlite
luarocks install luasql-odbc
You can also use source code installation. Lua Github source code address:https://github.com/keplerproject/luasql
Lua connecting to MySql database:
Example
require "luasql.mysql"
--Create environment object
env = luasql.mysql()
--Connect to database
conn = env:connect("database name","username","password","IP address",port)
--Set the database encoding format
conn:execute"SET NAMES UTF8"
--Perform 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
--Create environment object
env = luasql.mysql()
--Connect to database
conn = env:connect("database name","username","password","IP address",port)
--Set the database encoding format
conn:execute"SET NAMES UTF8"
--Perform 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