Lua Database Access
This article mainly introduces Lua's database operation library:LuaSQL. It is open source and supports databases such as ODBC, ADO, Oracle, MySQL, SQLite, and PostgreSQL.
This article introduces MySQL database connections.
LuaSQL can use LuaRocks to install; you can install the database driver you need as required.
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"
Installing LuaRocks on Windows:https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows
Install 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; the Lua GitHub source address:https://github.com/keplerproject/luasql
Lua connecting to a MySQL database:
Example
require
"luasql.mysql"
-- create environment object
env
=
luasql
.
mysql
(
)
-- connect to the 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 a file object
file
=
io.open
(
"role.txt"
,
"w+"
)
;
while
row
do
var
=
string.format
(
"%d %s\n"
,
row
.
id
,
row
.
name
)
(
var
)
file
:
write
(
var
)
row
=
cur
:
fetch
(
row
,
"a"
)
end
file
:
close
(
)
-- close the file object
conn
:
close
(
)
-- close the database connection
env
:
close
(
)
-- close the database environment