1. MySQL API를 이용한 예제 (TEST CODE)
※ MySQL API를 이용할 경우 이점
- Windows의 경우 ODBC를 설치하지 않고도 MySQL를 사용할 수 있다.
- Linux나 Unix 환경처럼 ODBC와 같은 범용 데이터베이스 연결 컨트롤을 사용할 수 없는 경우에도 사용가능하다.
01 | #define SOCKET int |
02 | |
03 | #include <mysql.h> |
04 | #include <string.h> |
05 | #include <stdio.h> |
06 | |
07 | #pragma comment(lib, "libmySQL.lib") |
08 | |
09 | #define DB_HOST "도메인 또는 IP" |
10 | #define DB_USER "유저명" |
11 | #define DB_PASS "암호" |
12 | #define DB_NAME "DB명" |
13 | |
14 | #define SQL_CREATE_TABLE "CREATE TABLE `mysql_api_test` (\ |
15 | `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,\ |
16 | `num` INT NULL ,\ |
17 | `string` VARCHAR( 20 ) NULL \ |
18 | ) TYPE = MYISAM ; " //" |
19 | #define SQL_INSERT_RECORD "INSERT INTO `mysql_api_test` ( `id` , `num` , `string` ) \ |
20 | VALUES (\ |
21 | NULL , '%d' , '%s' \ |
22 | ); " //" |
23 | #define SQL_SELECT_RECORD "SELECT * FROM `mysql_api_test`" |
24 | #define SQL_DROP_TABLE "DROP TABLE `mysql_api_test`" |
25 | |
26 | int main() |
27 | { |
28 | MYSQL *connection=NULL, conn; |
29 | MYSQL_RES *sql_result; |
30 | MYSQL_ROW sql_row; |
31 | int query_stat; |
32 | |
33 | char query[255]; |
34 | |
35 | mysql_init(&conn); |
36 |
37 | // DB 연결 |
38 | connection = mysql_real_connect(&conn, DB_HOST, |
39 | DB_USER, DB_PASS,DB_NAME, 3306,( char *)NULL, 0); |
40 | if (connection==NULL) |
41 | { |
42 | fprintf (stderr, "Mysql connection error : %s" , mysql_error(&conn)); |
43 | return 1; |
44 | } |
45 |
46 | // 테이블 생성 |
47 | query_stat=mysql_query(connection,SQL_CREATE_TABLE); |
48 | if (query_stat != 0) |
49 | { |
50 | fprintf (stderr, "Mysql query error : %s" , mysql_error(&conn)); |
51 | return 1; |
52 | } |
53 |
54 | // 레코드 삽입 |
55 | for ( int i=0;i<5;i++) |
56 | { |
57 | sprintf (query,SQL_INSERT_RECORD,100+i, "realmind는 마법사일까?" ); |
58 | query_stat = mysql_query(connection, query); |
59 | if (query_stat != 0) |
60 | { |
61 | fprintf (stderr, "Mysql query error : %s" , mysql_error(&conn)); |
62 | return 1; |
63 | } |
64 | } |
65 |
66 | // 셀렉트 |
67 | query_stat=mysql_query(connection,SQL_SELECT_RECORD); |
68 | if (query_stat != 0) |
69 | { |
70 | fprintf (stderr, "Mysql query error : %s" , mysql_error(&conn)); |
71 | return 1; |
72 | } |
73 |
74 | // 결과 출력 |
75 | sql_result=mysql_store_result(connection); |
76 | while ((sql_row=mysql_fetch_row(sql_result))!=NULL) |
77 | { |
78 | printf ( "%2s %2s %s\n" ,sql_row[0],sql_row[1],sql_row[2]); |
79 | } |
80 | mysql_free_result(sql_result); |
81 |
82 | // 테이블 삭제 |
83 | query_stat=mysql_query(connection,SQL_DROP_TABLE); |
84 | if (query_stat != 0) |
85 | { |
86 | fprintf (stderr, "Mysql query error : %s" , mysql_error(&conn)); |
87 | return 1; |
88 | } |
89 |
90 | // DB 연결 닫기 |
91 | mysql_close(connection); |
92 | return 0; |
93 | } |
※ MySQL API를 이용할 경우 이점
- Windows의 경우 ODBC를 설치하지 않고도 MySQL를 사용할 수 있다.
- Linux나 Unix 환경처럼 ODBC와 같은 범용 데이터베이스 연결 컨트롤을 사용할 수 없는 경우에도 사용가능하다.