LuaSQL Reference Manual |
Database connectivity for the Lua language |
LuaSQL is a simple interface from Lua to a DBMS. It has a collection of drivers to some popular databases (actually PostgreSQL and ODBC; Oracle, MySQL and ADO will be ready soon). LuaSQL defines a simple object-oriented API. All drivers should implement this common API, but each one is free to offer extensions.
LuaSQL defines one single global variable, a table called luasql. This table is used to store the initialization methods of the loaded drivers. This method is used to create an environment object which is used to create a connection object. A connection object can execute SQL statements and eventually create a cursor object which is used to retrieve data.
Each LuaSQL driver is composed by two files: a C source file that implements the driver functions; and a Lua script used to load the dynamic library. The host application can be statically linked with one or more drivers or they can be loaded dynamically by the corresponding Lua script (this requires the built-in loadlib function Lua 5 offers).
An environment object is created by calling the method with the same name of the driver (odbc, postgres etc.). For example, luasql.odbc(), will try to create an environment object using the ODBC driver.
And the output of this script should be:-- load driver require"postgres" -- create environment object env = assert (luasql.postgres()) -- connect to data source con = assert (env:connect("luasql-test")) -- reset our table res = con:execute"DROP TABLE people" res = assert (con:execute[[ CREATE TABLE people( name varchar(50), email varchar(50) ) ]]) -- add a few elements list = { { name="Jose das Couves", email="jose@couves.com", }, { name="Manoel Joaquim", email="manoel.joaquim@cafundo.com", }, { name="Maria das Dores", email="maria@dores.com", }, } for i, p in pairs (list) do res = assert (con:execute(string.format([[ INSERT INTO people VALUES ('%s', '%s')]], p.name, p.email) )) end -- retrieve a cursor cur = assert (con:execute"SELECT name, email from people") -- print all rows row = cur:fetch ({}, "a") -- the rows will be indexed by field names while row do print(string.format("Name: %s, E-mail: %s", row.name, row.email)) row = cur:fetch (row, "a") -- reusing the table of results end -- close everything cur:close() con:close() env:close()
Name: Jose das Couves, E-mail: jose@couves.com Name: Manoel Joaquim, E-mail: manoel.joaquim@cafundo.com Name: Maria das Dores, E-mail: maria@dores.com