1 / 19

7. Application 개발 (Database Programming)

7. Application 개발 (Database Programming). 서울시립대학교 전자전기컴퓨터공학부 김한준. Database Connectivity. 일반 프로그램에서 Database 에 접근 기본적으로 database 접근을 배려한 programming language 는 존재하지 않음 질의 결과를 프로그램내부에서 처리 Database 에서 질의한 결과를 프로그램 변수에 저장 및 조작함을 의미 하나의 응용프로그램으로 다양한 데이타베이스 접근

ashtyn
Télécharger la présentation

7. Application 개발 (Database Programming)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 7. Application 개발(Database Programming) 서울시립대학교 전자전기컴퓨터공학부 김한준

  2. Database Connectivity 일반 프로그램에서 Database에 접근 기본적으로 database 접근을 배려한 programming language는 존재하지 않음 질의 결과를 프로그램내부에서 처리 Database에서 질의한 결과를 프로그램 변수에 저장 및 조작함을 의미 하나의 응용프로그램으로 다양한 데이타베이스 접근 cf) device driver  database driver Database에 접근하기 위해서는 device driver 개념의 database driver가 필요함

  3. Problems • Heterogeneity • Access to Diverse DBMS • Impendence Mismatch • Query results (RDB)  Set • Program variable • Directly cannot deal with “Set” DBMS Database ?

  4. Field A Field B …. Row -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- DBMS Database Problems: Impedance Mismatch Program variable M_field_A M_field_B …

  5. Database Connectivity` 일반 프로그램에서 database에 접근 질의결과를 프로그램 내부의 데이터 변수를 가지고 조작, 처리 해결해야 할 일 하나의 응용프로그램으로 다양한 데이터베이스 접근 Database driver의 필요성 제공 Impendence Mismatch 문제를 해결해야 함 Query results (RDB)는 집합(Set) 일반 program의 변수는 “set”을직접 처리할 수 없음 Field A Field B …. Row -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- -------- -------------- ------- DBMS Database Program variable M_field_A M_field_B … DBMS Database ?

  6. Database와의 connection 방식 DBMS dependent API Client Program Client Program Client Program DB Client Application DB Server Application DBMS DBMS MiddleWare For DB DBMS Networking Module Database Database Database Client Side Server Side Client Side Server Side Uniform API가 필요 예) ODBC, JDBC 등

  7. Database에 대한 Uniform Interface (Middleware) Java Application • Open a connection • Sends a query statement • Retrieve results • Closes a connection • Creates a Connection session • Executes statement • Sends results • Close the session JDBC ODBC Perl DBI OLE DB DAO ADO … JDBC Manager Application JDBC Driver JDBC-ODBC Bridge JDBC Driver JDBC Driver Driver Manager ODBC Architecture ODBC Driver ODBC Driver ODBC Driver ODBC Driver ODBC Driver Client Side Native Driver Server Side Sybase Database Oracle Database MySQL Database Informix Driver Oracle Database MySQL Database MSSQL Database Sybase Database Client Side Server Side JDBC Architecture

  8. ODBC 기능 및 driver 활용 NameCard Database • 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 처리 Program code Application ODBC Architecture Driver Manager ODBC Driver ODBC Driver ODBC Driver ODBC Driver Oracle Database MySQL Database MSSQL Database Sybase Database ODBC Driver의 활용 (in Windows)

  9. Web과 Database연동 방식: CGI 방식 • CGI가 직접 DBMS에 접근해 데이터를 추출 • 구현 용이  기존의 웹서버 브라우저 그대로 사용 • One Request  One Process • Context switching overhead HTTP Request HTTP Request Ex) Apache + PHP Calls CGI DB Application Web Server Web Server DB Application Program Internet Internet 확장 API 방식 HTML HTML Results HTML Results • DB application program을 Web Server안에서 직접 구동 • DB Request  Web Server에서 처리 • Context switching overhead 없음 • 특정 web browser에 종속 HTML HTML Data Data

  10. Web과 Database연동 방식: Demon 방식 • Client에 있는 Java Applet이 직접 질의요청 DB requests Java Applet Demon HTTP Request HTTP Request Calls Web Server Web Server Remote Method Invocation Servlet Process Internet Internet Servlet 방식 HTML HTML Results HTML Results • DB application program을 Web Server가 대신 호출 • DB Request  Web Server에서 처리 • Context switching overhead 없음 • 특정 web browser에 독립 Query Results data HTML HTML Data Data

  11. Actions on Client & Server • Open a connection • Sends a query statement • Retrieve results • Closes a connection • Creates a Connection session • Executes statement • Sends results • Close the session Client Side Server Side

  12. Database Programming Example: ODBC API Code 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; } Make a connection More rows ? DB접속 Build SQL statement 질의준비 /요청 Close result set 변수매핑 Send SQL statement Close SQL statement 질의결과 출력 Programming 절차 Fetch Row Close connection DB종료

  13. Database Programming Example: Perl Code $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; Make a connection More rows ? DB접속 Build SQL statement 질의준비 /요청 Close result set Send SQL statement 변수매핑 및 질의결과출력 Close SQL statement Fetch Row Programming 절차 Close connection DB종료

  14. Database Programming Example: PHP Code DB접속 변수매핑 $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 More rows ? 질의준비 /요청 Build SQL statement 질의준비 /요청 Close result set Send SQL statement Close SQL statement Programming 절차 Fetch Row 질의결과 출력 Close connection DB종료

  15. 입문 예제 • PHP에서 select query이용하여 데이터베이스 데이터 조작하기 • Mysql_query(“select * • from student • where department = 1 and address = ‘seoul’”); • 실행 결과

  16. 이론 : 웹 데이터베이스 구조 • 웹 브라우저, 웹 서버, 스크립트 엔진, 데이터베이스 서버로 구성된 기본적인 웹 데이터베이스 구조 • 웹 데이터베이스 처리는 보통 다음과 같은 단계로 이루어 진다. • 1. 사용자의 웹 브라우저가 특정 웹 페이지에서 HTTP 요청을 보낸다. • 2. 웹 서버는 이 요청을 받고서 이를 처리하기 위해 PHP 엔진에 넘긴다. • 3. PHP는 MYSQL 서버에 연결해서 쿼리들을 보낸다. • 4. MYSQL 서버는 쿼리를 받아 처리하고 결과를 PHP 엔진에 되돌려 준다. • 5. PHP 엔진은 결과를 HTML 형식에 맞게 바꾼 후 웹 서버에 전달한다. • 6. 웹 서버는 결과를 브라우저에 전달하고 사용자는 검색 결과를 볼 수 있다. 1 2 3 브라우저 웹 서버 PHP 엔진 MYSQL 서버 6 5 4

  17. 이론 : 데이터베이스 접속 환경파일 작성 • 데이터베이스에 접속 하기 위해 필요한 정보를 파일로 관리 <? // 데이타베이스에 접속하는 경우 사용하는 설정 값들 $db_server = "localhost";// Mysql서버가 있는 서버 명 $db_user = "root";// 데이터베이스 사용자 $db_passwd = "apmsetup";// 접속 비밀번호 $db_name = "mobil"; // 사용할 데이터베이스 이름 // 위의 정보를 이용하여 데이타베이스에 접속함. $connect = mysql_connect($db_server, $db_user, $db_passwd) or die ("데이타베이스 접속실패"); // 데이터베이스 접속 mysql_select_db($db_name,$connect) or die("데이타베이스선택오류"); // 사용할 데이터베이스 선택 ?>

  18. 실습 : PHP를 이용한 SEARCH, INSERT QUERY • SEARCH • INSERT • Mysql_query(“SELECT id, name, department • From student • Where Grade = (Mysql_query(“SELECT MAX(Grade) • FROM student)”)” • ); Mysql_query()는 데이터베이스에 SQL 문장의 실행을 요청함. Student 테이블의 Grade의 최대 값을 가지는 학생의 id, name, department(학과)를 출력 • Mysql_query(“INSERT INTO student1 (Mysql_query(“SELECT * • FROM student • WHERE id = 11 and address = ‘seoul’ ”)”) • ); Student 테이블의 id가 11이고 address가 ‘seoul’인 학생의 정보를 검색하여 student1테이블에 삽입

  19. 실습 : PHP를 이용한 DELETE, UPDATE QUERY • DELETE • UPDATE • Mysql_query(“DELETE • FROM student • WHERE grade = 3 and department = 2); Student 테이블의 grade(학년)가 3이고 department(학과)가 2인 학생의 정보를 삭제 • Mysql_query(“UPDATE student • SET address = (Mysql_query(“SELECT address • FROM student • WHERE id = 2”)) • WHERE grade = 3 and department = 2”); Student 테이블의 grade(학년)가 3이고 department(학과)가 2인 학생의 주소를 id가 2인 학생의 주소로 변경

More Related