English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Lua Database Access

This article mainly introduces the Lua database operation library for everyone:LuaSQL. It is open source and supports the following databases: ODBC, ADO, Oracle, MySQL, SQLite, and PostgreSQL.

This article introduces the database connection of MySQL.

LuaSQL can be used LuaRocks You can install the database driver you need according to your needs.

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"

Install 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 use the source code installation method, Lua Github Source Code Address:https://github.com/keplerproject/luasql

Lua Connect to MySql Database:

require "luasql.mysql"
--5.2 After version, require no longer defines global variables, and its return value needs to be saved.
--Need to be written as:
--luasql = 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 Operation
cur = conn:execute("select * from role)
row = cur:fetch({}, "a")
--File Object Creation
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