Latest web development tutorials

Lua database access

In this paper, we describe the operation of the database library Lua: LuaSQL . He is open source, there is support for database: ODBC, ADO, Oracle, MySQL, SQLite and PostgreSQL.

This article is to introduce the database connection MySQL.

LuaSQL can use LuaRocks to be installed you need to install database drivers as needed.

LuaRocks installation methods:

$ wget
$ 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, PUC-Rio
> require "socket"

Installation LuaRocks under the Window:

Install a 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, Lua Github Source Address:

Lua connect 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 ="role.txt","w+");

while row do
    var = string.format("%d %s\n",,



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

file:close()  --关闭文件对象
conn:close()  --关闭数据库连接
env:close()   --关闭数据库环境