* 메인 사이트 :
http://www.keplerproject.org/luasql/
http://www.keplerproject.org/luasql/
- 현재 mysql, postgresql, oracle 지원
- 연결풀링 지원안함. (별도 구현 필요)
2 간단빌드방법 #
포함된 라이브러리는 사용하기 꽤 성가십니다. 다음과 같이 하면 간단하게 사용할 수 있습니다. (여기서는 ODBC를 예로 빌드하였습니다) 우선 배포본 소스 압축을 풀고 makefile을 다음과 같이 만듭니다. 여기서는 lua 라이브러리가 /usr/local/include, /usr/local/lib에 설치되어있다고 가정하였습니다. 아니라면 적당히 수정하세요.
COMPILE_FLAGS=-D_MT -Wall -mcpu=pentium -O2 -funroll-loops -ffast-math -fomit-frame-pointer -I/usr/local/include LINK_FLAGS=-L/usr/local/lib -llua -llualib -lkernel32 -luser32 -lodbc32 OBJS=luasql.o ls_odbc.o compile: $(OBJS) gcc -shared $(OBJS) -o luasql.dll odbc.def $(LINK_FLAGS) strip luasql.dll clean: rm *.o .c.o: gcc $(COMPILE_FLAGS) -I. -o $@ -c $<그다음 odbc.def라는 화일을 새로만들어 다음과 같이 적습니다.
LIBRARY luasql.dll DESCRIPTION "LuaSQL driver for odbc" VERSION 2.0b EXPORTS luasql_libopen_odbc그런다음 make하면 luasql.dll이란 화일을 얻을 수 있습니다. 루아에서 luasql을 사용하려면 다음과 같이 합니다.
loadlib("luasql.dll", "luasql_libopen_odbc")()
이제 메뉴얼에 적힌데로 진행하면 됩니다.
3 개요 #
luaSQL은 DB시스템과의 연결을 위한 간단한 루아 인터페이스입니다. 몇몇 인기있는 데이타 베이스에 대한 드라이버도 가지고 있습니다(현재 postgresql, ODBC, mysql, oracle; ADO는 곧 지원예정) luaSQL은 간단한 객체지향적 API를 가지고 있습니다. 모든 드라이버들은 미리 지정된 일반 API를 구현해야만 하며, 몇몇 추가기능은 확장함수형태로 제공됩니다.
luaSQL은 단하나의 전역 변수인 luasql이라는 테이블 변수를 정의합니다. 이 테이블은 로딩된 드라이버의 초기화 메소드를 담기위해 사용됩니다. 이 메소드는 환경 객체를 생성하는데 사용되며, 이 객체를 사용하여 연결객체를 생성합니다. 연결객체는 SQL 문장을 실행할 수 있으며 데이타를 받기위해 커서 객체를 생성합니다.
각각의 luaSQL 드라이버는 두개의 화일로 구성되어있습니다 : 드라이버 함수를 구현한 C 소스 화일과 DLL을 적재하기 위해 사용되는 루아 스크립트 화일. 호스트 어플리케이션은 사용할 DB에 해당하는 드라이버를 정적 혹은 동적 링크해야만 합니다.
4 환경객체 #
환경객체는 luasql 테이블내에 해당 DB명과 같은 이름의 초기화 메소드를 실행함으로서 생성됩니다. 예를 들면, luasql.odbc()는 ODBC 드라이버에 해당하는 환경객체를 생성하여 반환합니다.
4.1.2 env:connect(sourcename[,username[,password]]) #
sourcename에 username과 password를 사용하여 지정된 데이타 소스에 연결합니다. 연결되면 해당 연결객체가 반환됩니다. postgresql/mysql 확장 함수를 참조하세요.
5.1.5 conn:setautocommit(boolean) #
자동 commit 모드를 켜거나 끕니다. 이것은 mysql과 같이 트랜젝션을 지원하지 않는 경우에는 동작하지 않을 수 있습니다.
6 커서객체 #
커서객체는 SQL문의 실행결과로 반환된 데이타를 담고 있는 객체입니다. 이 객체는 conn:execute()에 의해 반환됩니다. postgresql/oracle 확장 함수를 참조하세요.
6.1.2 cur:fetch([table[,modestring]]) #
결과의 다음 열을 반환합니다. 매개변수없이 fetch를 호출하면, 함수의 반환값으로 결과를 반환합니다. fetch의 매개변수로 테이블을 지정하면, 결과는 테이블안에 복사되고, (편의를 위해) 해당 테이블이 반환됩니다. 이 경우, mode 옵션을 사용할 수 있습니다. 이 옵션은 단지 결과 테이블을 어떻게 구성할 것인지를 지시하는 내용을 담은 문자열입니다. 모드 문자열은 다음을 담고 있습니다:
숫자 인덱스를 사용하면 select 명령내의 각 필드의 위치를 의미하게 됩니다; 알파벳 인덱스일 경우 필드명을 나타내게 됩니다.
옵션 테이블 매개변수는 다음 열을 저장하는데 사용될 테이블입니다. 이는 여러번의 fetch작업동안 하나의 테이블을 재활용할 수 있도록 해주며, 이렇게 함으로서 (테이블의 쓸데없는 재생성을 줄임으로서)전반적인 성능을 개선할 수 있습니다. 결과값들에 대한 타입에 대해서 확실하게 보장하지는 않습니다 - 각각의 타입은 드라이버에 의해 적당한 루아 타입으로 변환되거나 그냥 저장됩니다. 최신 구현(2.0a)에서는, postgresql과 mysql 드라이버는 모든 값을 문자열로 반환하며, ODBC와 oracle는 적당한 루아 타입으로 변환되며 반환됩니다. fetch의 반환값은 위에서 언급한데로 데이타를 반환하며, 더이상 데이타가 없는경우 nil을 반환합니다.
| "n" | 결과 테이블은 숫자 인덱스를 사용합니다(기본값) |
| "a" | 결과 테이블은 알파벳 인덱스를 사용합니다. |
7 PostgreSQL 확장함수 #
Besides the basic functionality provided by all drivers (see manual), the Postgres driver also offers these extra features:
7.1 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
7.2 cur:numrows() #
This additional method returns the number of rows in the query result.
See also: cursor objects
8 MySQL 확장함수 #
Besides the basic functionality provided by all drivers (see manual), the MySQL driver also offers these extra features:
8.1 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.
9 Oracle 확장함수 #
Besides the basic functionality provided by all drivers (see manual), the Oracle driver also offers this extra feature:
10 예제 #
다음은 라이브러리의 사용법을 보여주기위한 간단한 예제입니다.
-- 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








