database 활용을 위한 기초 이론 1. database 의 개요 2. data modeling 3. database...
TRANSCRIPT
Database 활용을 위한 기초 이론
1. Database 의 개요2. Data Modeling3. Database programming 의
원리
강의제목◦ Database programming 의 원리
목표◦ Web 과 database 의 연동의 원리를 이해하고 web script 언어를 이용하여
database 를 조작하는 방법을 터득 목차
◦ 개요◦ 연동의 문제점◦ Database 와의 연결방식◦ Middleware: ODBC, JDBC, Perl DB◦ Programming 예제◦ 연동 방식
3
일반 프로그램에서 database 에 접근◦ 질의 결과를 프로그램 내부의 데이터
변수를 가지고 조작 , 처리
해결해야 할 일◦ 하나의 응용프로그램으로 다양한
데이터베이스 접근 Database driver 의 필요성 제공
◦ Impendence Mismatch 문제를 해결해야 함 Query results (RDB) 는 집합 (Set) 일반 program 의 변수는 “ set” 을
직접 처리할 수 없음
DBMS
Database?
M_field_AM_field_B
…
Program variable
-------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- -------
-------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- --------------- -------------- -------
RowField A Field B ….
DBMSDBMS
Database
4
DB ServerApplication
DB ServerApplication DBMSDBMS
Database
Client ProgramDBMS dependent
API
Server SideClient Side
DB ClientApplication
DB ClientApplication
DBMSDBMS
Client Program
Server SideClient Side
NetworkingModule
NetworkingModule
Database
MiddleWareFor DB
MiddleWareFor DB DBMSDBMS
Database
Client Program
Uniform API 가 필요
예 ) ODBC, JDBC 등
Uniform API 가 필요
예 ) ODBC, JDBC 등
5
JDBCODBCPerl DBIOLE DBDAOADO…
Application
Driver Manager
ODBCDriver
ODBCDriver
ODBCDriver
ODBCDriver
OracleDatabase
MSSQLDatabase
SybaseDatabase
MySQLDatabase
ODBC Architecture
Java Application
JDBC Manager
JDBCDriver
JDBC-ODBCBridge
JDBCDriver
JDBCDriver
ODBCDriver
NativeDriver
SybaseDatabase
MySQLDatabase
InformixDriver
OracleDatabase
JDBC Architecture
1. Open a connection
2. Sends a query statement
3. Retrieve results
4. Closes a connection
1. Open a connection
2. Sends a query statement
3. Retrieve results
4. Closes a connection
1. Creates a Connection session
2. Executes statement
3. Sends results
4. Close the session
1. Creates a Connection session
2. Executes statement
3. Sends results
4. Close the session
Client Side Server Side
Client Side
Client Side
ServerSide
ServerSide
6
Application◦ DB 접속 , 세션 요청◦ SQL 결과를 위한 저장 영역 및 데이터 포맷 정의◦ 결과 요청◦ 에러 처리◦ Query/Commit/Rollback 요청◦ DB 접속 종료
Driver Manager (ODBC.DLL)◦ DB (data) source name 을 특정 driver 의 DLL 로
mapping◦ ODBC 호출 검증
DB Driver◦ Data source 에 연결 설정◦ Data source 에 질의 요청 전송◦ Data format 변환◦ Query results 를 application 쪽으로 반환◦ Error code 리턴◦ Cursor 선언 및 조작◦ Transaction 처리
Application
Driver Manager
ODBCDriver
ODBCDriver
ODBCDriver
ODBCDriver
OracleDatabase
MSSQLDatabase
SybaseDatabase
MySQLDatabase
ODBC Architecture
NameCardDatabase
Programcode
Programcode
ODBC Driver 의 활용 (in Windows)
7
InternetCGI DB
Application
HTML Data
HTTP Request
HTML Results
Calls
HTML
WebServer
•CGI 가 직접 DBMS 에 접근해 데이터를 추출• 구현 용이 기존의 웹서버 브라우저 그대로 사용• One Request One Process• Context switching overhead
•CGI 가 직접 DBMS 에 접근해 데이터를 추출• 구현 용이 기존의 웹서버 브라우저 그대로 사용• One Request One Process• Context switching overhead
InternetDB
ApplicationProgram
HTML Data
HTTP Request
HTML Results
WebServer
Ex) Apache + PHP
• DB application program 을 Web Server 안에서 직접 구동• DB Request Web Server에서 처리• Context switching overhead 없음• 특정 web browser 에 종속
• DB application program 을 Web Server 안에서 직접 구동• DB Request Web Server에서 처리• Context switching overhead 없음• 특정 web browser 에 종속
8
InternetRemoteMethod
Invocation
HTML Data
HTTP Request
HTML Results
WebServer
Demon
Query Results
DB requestsJava
Applet
• Client 에 있는 Java Applet이 직접 질의요청• Client 에 있는 Java Applet이 직접 질의요청
InternetServletProcess
HTML Data
HTTP Request
HTML Results
WebServer
data
Calls
HTML
• DB application program 을 Web Server 가 대신 호출• DB Request Web Server에서 처리• Context switching overhead 없음•특정 web browser 에 독립
• DB application program 을 Web Server 가 대신 호출• DB Request Web Server에서 처리• Context switching overhead 없음•특정 web browser 에 독립
9
Int example (UCHAR *server, UCHAR *uid, UCHAR *pwd)
{
HENV henv;
HDBC hdbc;
HSTMT hstmt;
UCHAR id[10], name[100], select[200];
SDWORD namelen, idlen;
RETCODE rc;
SQLAllocEnv(&henv);
SQLAllocConnect(henv, &hdbc);
rc=SQLConnect(hdbc, server, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return printf(“can’t connect”);
SQLAllocStmt(hdbc, &hstmt);
lstrcpy((LPTSTR) select, “SELECT InstructId, Name FROM Instructor”);
if (SQLExecDirect(hstmt, select, SQL_NTS) != SQL_SUCCESS)
return printf(“can’t exec direct”);
printf(“InstructorID Name\n”);
SQLBindCol(hstmt, 1, SQL_C_CHAR, id, (SDWORD)sizeof(id), &idlen);
SQLBindCol(hstmt, 2, SQL_C_CHAR, name, (SDWORD)sizeof(name), &namelen);
while(TRUE){
rc = SQLFetch(hstmt);
if (rc != SQL_NO_DATA_FOUND) printf(“%-12s %-9s\n”, id, name);
else break;
}
SQLTransact(henv, hdbc, SQL_COMMIT);
SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv);
return TRUE;
}
DB 접속
질의준비/ 요청
변수매핑
질의결과출력
DB 종료
Make a connection
Build SQL statement
Send SQL statement
Fetch Row
More rows ?More rows ?
Close result set
Close SQL statement
Close connection
Programming 절차
10
$dsn = "dbi:Oracle:host=swan;sid=ora8";$ENV{ORACLE_HOME} = "/usr4/ora8/app/oracle/product/8.0.4";$ENV{ORA_NLS32} = "$ORACLE_HOME/ocommon/nls/admin/data";$user = "catalog";$password = "stop";$dbh = DBI->connect($dsn, $user, $password) || die "$DBI::errstr";
$sql_doc = "SELECT did, file_path, input_date FROM docs“;
#print "<font color=black size=2>$sql_doc</font>\n";
$sth = $dbh->prepare($sql_doc) || die "DBI::errstr";$sth->execute() || die "DBI::errstr";
while (($did, $file_path, $input_date) = $sth->fetchrow_array()){# print "[ 문서번호 ] $did [ 화일명 ] $file_path [ 입력날짜 ]
$input_date\n","<br>\n";;}$dbh->do (“insert into $ 유 _name values (“perl”, “database”,
‘2000/10/17’, …);$dbh->do (“drop table students”);$sth->finish;$dbh->disconnect;
DB 접속
질의준비/ 요청
변수매핑 및 질의결과출력
DB 종료
Make a connection
Build SQL statement
Send SQL statement
Fetch Row
More rows ?More rows ?
Close result set
Close SQL statement
Close connection
Programming 절차
11
$host = "localhost";$user = "php";$password = "12345"; $connect = mysql_connect($host, $user, $password);mysql_select_db('php_db',$connect); $bookname = $_POST["bookname"]; $bookauthor = $_POST["bookauthor"];
$pubyear = $_POST["pubyear"];$position1 = $_POST["position1"]; $position2 = $_POST["position2"]; $sql = "insert into bookmanage values('$bookname',
'$bookauthor' ,'$pubyear‘ ,'$position1','$position2')";
mysql_query($sql,$connect);
$connect = mysql_connect($host,$user,$password);mysql_select_db('php_db', $connect); $sql = "select * from bookmanage";$result = mysql_query($sql,$connect);$rows = mysql_num_rows($result); echo"<table border=1>";echo"<tr><th> 책이름 <th> 책저자 <th> 출판년도 <th> 위치 1<th> 위치 2";for($i=0; $i<$rows; $i++) { $record = mysql_fetch_array($result); echo "<tr>"; echo "<td>$record[bookname]"; echo "<td>$record[bookauthor]"; echo "<td>$record[pubyear]"; echo "<td>$record[position1]"; echo "<td>$record[position2]"; }echo"</table>";mysql_close($connect);?>
Make a connection
Build SQL statement
Send SQL statement
Fetch Row
More rows ?More rows ?
Close result set
Close SQL statement
Close connection
DB 접속
질의준비/ 요청
질의결과출력
DB 종료
변수매핑
질의준비/ 요청
Programming 절차