Lua database access


Release date:2023-10-10 Update date:2023-10-13 Editor:admin View counts:330

Label:

Lua database access

This article mainly introduces the Lua database operation library: LuaSQL. He is open-source and supports databases such as ODBC, ADO, Oracle, MySQL, SQLite, and PostgreSQL.

This article introduces to you MySQL the database connection.

LuaSQL use LuaRocks to install the databasedriver you need to install 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"

Install LuaRocks: https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows under Window

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 address: https://github.com/keplerproject/luasql

Lua connection MySql database:

Example

require "luasql.mysql"
--Creating Environment Objects
env = luasql.mysql()
--Connect to database
conn = env:connect("Database name, username, password, IP address, port)
--Set the encoding format for the database
conn:execute"SET NAMES UTF8"
--Perform database operations
cur = conn:execute("select * from role")
row = cur:fetch({},"a")
--Creating File Objects
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()   --Shutdown Database Environment

Powered by TorCMS (https://github.com/bukun/TorCMS).