|
LuaSQL Reference Manual
|
Database connectivity for the Lua language
|
home ·
environment ·
connection ·
cursor ·
extensions ·
example
Introduction
LuaSQL is a simple interface from Lua to a DBMS.
It has a collection of drivers to some popular databases
(actually PostgreSQL, ODBC, MySQL and Oracle; 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.
These methods are 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).
LuaSQL is free software.
Environment objects
An environment object is created by calling the driver's initialization
function that is stored into the table luasql 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.
Methods
- env:close()
Closes the environment env.
Only successful if all connections pertaining to it were closed first.
- env:connect(sourcename[,username[,password]])
Connects to a data source specified in sourcename using
username and password if they are supplied.
See also: PostgreSQL,
and MySQL extensions.
Returns: a connection object.
Connection objects
A connection object contains specific attributes and parameters of a single
data source connection.
A connection object is created by calling the
environment:connect
method.
Methods
- conn:close()
Closes the connection conn.
Only successful if all cursors pertaining to it were closed first.
- conn:commit()
Commits the current transaction.
- conn:execute(statement)
Executes the given SQL statement.
Returns: a cursor object
if there are results, or the number of rows affected by the command otherwise.
- conn:rollback()
Rolls back the current transaction.
- conn:setautocommit(boolean)
Turns on or off the "auto commit" mode.
This feature might not work on database systems that don't implement
transactions.
Cursor objects
A cursor object contains methods to retrieve
data resulting from an executed statement.
A cursor object is created by using the
connection:execute
function.
See also PostgreSQL
and Oracle extensions.
Methods
- cur:close()
Closes this cursor.
- cur:fetch([table[,modestring]])
Retrieves the next row of results.
If fetch is called without parameters,
the results will be returned to the caller directly.
If fetch is called with a table, the results will be copied
into the table and this table will be returned (for convenience).
In this case, an optional mode parameter can be used.
It is just a string indicating how the result table should be made.
The mode string can contain:
- "n" the resulting table will have numerical indices (default)
- "a" the resulting table will have alphanumerical indices
The numerical indices are the positions of the fields in the select
statement;
the alphanumerical indices are the names of the fields.
The optional table parameter is a table that should be
used to store the next row.
This allows the use of a unique table for many fetches which
can improve the overall performance.
There is no guarantee about the types of the results
-- they can be converted to adequate Lua types by the driver or not.
In the current implementation (2.0b),
the PostgreSQL and MySQL drivers returns all values as strings
while the ODBC and Oracle drivers converts them to Lua types.
Returns: data, as above, or nil if there are no more rows.
- cur:getcolnames()
Returns: a list of column names.
- cur:getcoltypes()
Returns: a list of column types.
PostgreSQL extensions
Besides the basic functionality
provided by all drivers (see manual), the Postgres driver also offers
these extra features:
- env:connect(sourcename[,username[,password[,hostname[,port]]]])
In the PostgreSQL driver, this method has two other optional parameters
that indicate the hostname and port to connect.
Also, the first parameter can contain all connection information,
as stated in the documentation for PQconnectdb function
in the PostgreSQL manual
(e.g. environment:connect("dbname=<name> user=<username>"))
See also: environment objects
- cur:numrows()
This additional method returns the number of rows in the query result.
See also: cursor objects
MySQL extensions
Besides the basic functionality
provided by all drivers (see manual),
the MySQL driver also offers these extra features:
- env:connect(sourcename[,username[,password[,hostname[,port]]]])
In the MySQL driver, this method has two other optional parameters
that indicate the hostname and port to connect.
See also: environment objects
Note: This driver is compatible to version 4.1 of MySQL API,
with support to BDB and INNODB tables.
MySQL has types of tables that don't support transactions,
so with these types, the methods setautocommit, commit
and rollback don't work.
Oracle extensions
Besides the basic functionality
provided by all drivers (see manual), the Oracle driver also offers
this extra feature:
- cur:numrows()
This additional method returns the number of rows in the query result.
See also: cursor objects
Example
Below is a small sample code displaying the basic use of the library.
-- 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()
And the output of this script should be:
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
Contents
home ·
environment ·
connection ·
cursor ·
extensions ·
example
Last modified on
Fri Sep 12 18:31:45 BRT 2003