offfff

[MySQL C API] 2. 데이터베이스 생성(Creating a database) 본문

프로그래밍

[MySQL C API] 2. 데이터베이스 생성(Creating a database)

offfff 2016. 8. 12. 09:00

1. 다음과 같은 순서로 프로그래밍 한다


- Connection hadle structure 초기화

- MySQL Server와 연결

- Query 문 실행

- 연결 종료




2. 소스코드


아래 코드는 MySQL 데이터베이스 서버에 

'testdb'라는 새로운 DB를 생성하는 코드이다.


#include <my_global.h>

#include <mysql.h>


int main(int argc, char **argv)

{

//# Connection handle structure 선언 및 초기화

MYSQL *con = mysql_init(NULL);

if (con == NULL)

{

fprintf(stderr, "%s \n", mysql_error(con));

exit(1);

}


//# MySQL Server와 연결

// root : 서버에 접속할 사용자 ID

// root_pswd : 해당 아이디의 비밀번호

if (mysql_real_connection(con, "localhost", "root", "root_pswd",

NULL, 0, NULL, 0) == NULL)

{

fprintf(stderr, "%s \n", mysql_error(con));

mysql_close(con);

exit(1);

}


//# Query 문 실행

if (mysql_query(con, "CREATE DATABASE testdb"))

{

fprintf(stderr, "%s \n", mysql_error(con));

mysql_close(con);

exit(1);

}


//# 연결 종료

mysql_close(con);

exit(0);

}


mysql_init, mysql_real_connection로 프로그램을 시작하여 서버를 연결하고,

mysql_close로 프로그램 종료시 서버와의 연결 종료를 한다.

mysql_query에서 데이터베이스를 생성하기 위해서는

mysql_real_connection에 사용자를 root로 해서 연결해야 한다.


실질적으로 데이터베이스를 수정하는데에는 mysql_query를 사용한다.

따라서 쿼리문을 익히는게 MySQL 프로그래밍의 절반이라고 볼 수 있을것 같다.




아래 링크를 참고하여 번역 및 수정함 

http://zetcode.com/db/mysqlc/