Wednesday, April 22, 2009

Connecting Oracle Database with oracle instant client using PHP in Linux

We can connect Oracle db without oracle client if only we can use instant client instead. But this is for 10g or later version of db.

1. You need to have an account for www.oracle.com. Create a new through Register for a free Oracle Web account) .

2. Choose which release of Oracle instant client you need here.

3. Accept license agreement, find the version you need, click to download. (I chose version 10.2 of basic, sdk and sqlplus package. Note that some version may not work in your system.)

4. Install it. You can install it using rpm or manually using .zip files.

5. If you downloaded sqlplus package and running on linux, you can check whether it works properly with command '>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:[instant client's path]; ./sqlplus --help' in instantclient directory.

6. Now's the time to test db connection using sqlplus. Make text file with the name 'tnsnames.ora' with connect information like below.

YOURNAME =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = XXX.XXX.XXX.XXX)(PORT = XXXX))
)
(CONNECT_DATA =
(SID = XXXXX)
)
)

7. Set environment variables like below.

> export ORACLE_HOME=
> export TNS_ADMIN=

8. > now try to connect with id/pw. Does it work? Fine!

9. To make it work, you should recompile php module with the option like below.

--with-oci8=instantclient,

10. Check whether follow env variables set set properly

export TNS_ADMIN=/yoursystem/yourpath # where tnsnames.ora exists
export NLS_LANG=KOREAN_KOREA.UTF8 # set encoding for your locale

11. Check with . If you can find oci8 section in the information, it's done.

12. Now you can connect to oracle db using php functions. Let's see sample code.


<?

// ORA_SERVER : defined in tnsnames.ora

// Connect

$conn = oci_connect('user', 'pass', 'ORA_SERVER');

if (!$conn) {

    $e = oci_error();

    print htmlentities($e['message']);

    exit;

}

// Execute query

$query  = 'SELECT * FROM SAMPLETABLE';

$stid   = oci_parse($conn, $query);

if (!$stid) {

    $e = oci_error($conn);

    print htmlentities($e['message']);

    exit;

}

$r = oci_execute($stid, OCI_DEFAULT);

if (!$r) {$e = oci_error($stid);

    echo htmlentities($e['message']);

    exit;

}



// Fetch results

while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) {

    foreach ($row as $item) {

        print ($item?htmlentities($item):'&nbsp;').'<br>';

    }

}



// Close

oci_close($conn);

?>

Monday, March 2, 2009

XML Document Validation Tool

If that's just for debug and development purpose, simply use xmllint.

> xmllint yourDocument.xml

Tuesday, February 17, 2009

제목 보고 당했다.


"새표준 C C99" C99 표준 번역서 인줄 알고 냉큼 샀는데, C 기초 프로그래밍 책이다.

이런,.

Thursday, February 12, 2009

Sunday, October 26, 2008

Backtracking

백트래킹은 주어진 어떤 집합에 대해 조건을 만족하는 모든 부분집합(subset)을 구하는 정형화된 알고리즘이다.

/*
a[] : 답중 하나가 되는 부분 집합을 저장할 공간
n : 전체 집합의 크기
k : 현재 집합의 크기
candidates[] : 조건들 (예, 포함되거나 안되거나)
*/
void process_solution(int a, int k)
{
for (int i = 1; i <= k;)
if (a[i] == 1) printf ("...", i);
}
void construct_candidates( ... c, *nc)
{
c[...] = condition
...
*nc = X; // number of conditions
return;
}
backtrack(a[], k, n)
{
if (k == n)
process_solution(a, k);
else
k++;
construct_candidates(c, &nc);
for (int i = 0; i < nc; i++)
a[k] = c[i]; // set condition
backtrack(a, k, n);
}
int main()
{
a = arr[MAXSIZE];
backtrack(a, 0, n);
}

Minimizing Memory Cost

프로그램이 사용하는 메모리를 절약하기 위한 방법들에 대해 정리해 보자.
  • 일단 단순해져야 한다.
    메모리의 구조를 단순하게 하면 크기도 줄어들고 실행속도도 빨리질 수 있다. (세금 계산 테이블을 메모리에 넣는 대신 이를 표현하는 하나의 함수를 사용할 수 있다)
  • 메모리 절약을 위해 사용되는 기법들은 아래와 같다.
    • Sparse data structure
      는 대부분의 엔트리가 같은 값을 가지는 데이터 구조를 의미하는데, 이를 리스트와 같은 자료구조를 사용하면 메모리를 절약할 수 있다. 혹은 같은 값을 가지는 부분만 떼어 내어 별도로 저장하므로 같은 값을 중복으로 저장하는 overhead를 줄일 수 있다.
    • 데이터 압축
      은 말그대로 압축을 하거나, 한 자료 타입안에 여러 데이터를 동시에 넣는 방법이다. (두 지점사이의 거리를 나타내는 행렬, 좌표 등)
    • 할당 정책의 변경
      을 통해 메모리를 절약할 수 있다. 공간을 정적으로 미리할당하지 않고 필요할 때 동적으로 할당해주는 것을 예로 들 수 있다.
  • 물론 메모리 절약에서도 Amdahl's law 가 적용된다. 특정 데이터 구조가 전체 메모리 공간의 대부분을 차지하는 경우를 찾아 개선하면 효율적으로 메모리를 절약할 수 있다.
  • 때로는 메모리 절약을 위해 성능을 희생해야하는 Trade-off 가 발생한다.

Wednesday, October 22, 2008

Using Macro is not always faster.

함수 콜하는 부분을 매크로로 치환하면 일반적으로 성능이 빨라진다. 그러나 항상 그렇지는 않다.


#define MAX(a,b) ((a) > (b) ? (a) : (b))

float arrmax(int n)
{
if (n == 1)
return x[0];
else
{
return MAX(x[n-1], arrmax(n-1));
}
}

위 코드는 매우 느리다. 배열의 최대값을 리턴하는 코드인데, 배열의 크기가 30개만 넘어가도 실행 속도가 수초이상 걸리게 된다. 왜냐하면 매크로 부분이 x[n-1] > arrmax(n-1) ? x[n-1] : arrmax(n-1) 로 치환되면서 수행시간이 (함수가 호출되는 횟수가) 매크로 대신 함수로 구현할 때 보다 O(n) 에서 O(2^n) 이 되기 때문이다. 재귀적 호출에서 이런 실수는 상당한 성능저하를 낳게 되니 주의 하자.