Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Lua database access


May 12, 2021 Lua


Table of contents


Lua database access

This article focuses on the operating library of the Lua database: LuaSQL. He is open source and supports databases such as ODBC, ADO, Oracle, MySQL, SQLite, and PostgreSQL.

This article introduces mySQL's database connection.

LuaSQL can use LuaRocks to install the database drivers 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 under Window: 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 installation method, Lua Github source address: https://github.com/keplerproject/luasql

Lua connects to the MySql database:

require "luasql.mysql"

--创建环境对象
env = luasql.mysql()

--连接数据库
conn = env:connect("数据库名","用户名","密码","IP地址",端口)

--设置数据库的编码格式
conn:execute"SET NAMES UTF8"

--执行数据库操作
cur = conn:execute("select * from role")

row = cur:fetch({},"a")

--文件对象的创建
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()  --关闭文件对象
conn:close()  --关闭数据库连接
env:close()   --关闭数据库环境