"Mysql DB안에 있는 일정 조건의 데이터를 일정한 시간에 조작하고 싶다. 이 프로그램은 C언어로 만들어야 한다.." 라는 문제를 만났다면 2가지를 생각해야 합니다.
Crontab에 관련된 이야기를 조금 미루고 지금은 Mysql Library에 관련된 이야기를 하려고 합니다..
언제나 그렇듯.. 사용하기 위해서는 먼저 설치(mysql)되어 있어야만 합니다. ^^
프로그램의 가장 쉬운 이행방법은 간단한 샘플 소스를 보는 것이기 때문에 샘플 소스를 보여드리도록 하겠습니다.
우선 makefile의 소스입니다.. makefile에 대해서도 나중에 이야기 할 시간이 있을 듯 합니다.
현재 Test를 진행한 서버의 mysql.h파일은 /usr/local/mysql/include/mysql안에 있습니다. 보통 mysql를 설치할때 prefix롤 설정된 곳에 있을 가능성이 큽니다. ^^
다른 프로그램에서 사용하던 makefile를 수정한 것이라서 깔끔하지 못한부분이 있습니다.
CC = gcc
OPTIONS = -o
SOURCES = test.c
OBJECTS = test.o
HEADERS =
CFLAGS = -Wall
LIBS = '-L/usr/local/mysql/include/mysql' '-L/usr/local/mysql/lib/mysql' '-lmysqlclient'
all : $(OBJECTS)
$(CC) $(OPTIONS) test $(CFLAGS) $(OBJECTS) $(LIBS)
backup : $(SOURCES) $(HEADERS) makefile
tar cvzf - $(SOURCES) $(HEADERS) makefile > backup.tar.gz
clean :
rm -f *.o test
prev :
touch test
이제 Mysql 테이블 형태를 보도록 하겠습니다.
그럼 이제 드디어 mysql library를 연결할 C파일을 만들도록 하죠 이름을 test.c라고 하겠습니다.
#include <stdio.h>
#include <stdlib.h>
#include "/usr/local/mysql/include/mysql/mysql.h"
/* gcc test.c -L/usr/local/mysql/include/mysql -L/usr/local/mysql/lib/mysql -lmysqlclient */
/* C to MySQL Program */
int main(int argc, char *argv[])
{
MYSQL mysql; //sets up the definition for MySQL
/*
* defines and names a result set based on the definitions for MYSQL_RES in mysql.h
* The results are to be stored in the array results, which will be an array of rows from MySQL
*/
MYSQL_RES *result;
//uses the definition for MYSQL_ROW to establish the variable row, which will be an array of columns from MySQL
MYSQL_ROW row;
char* query;
//initializes the connection to MySQL using the variable mysql defined at the beginning of the main function
if(!mysql_init(&mysql)){
fprintf(stderr, "Cannot initialize MYSQL\n");
exit(0);
}
/*
*mysql_real_connect(&mysql, "localhost", "user", "password", "db1", 0, NULL, 0))
*/
if(!mysql_real_connect(&mysql, "localhost", "root", "root123", "Ep_Spider", 0 , NULL, 0))
{
fprintf(stderr, "%d: %s \n", mysql_errno(&mysql), mysql_error(&mysql));
exit(0);
}
query = "SELECT * FROM `test` WHERE 1";
if(mysql_query(&mysql, query)){
fprintf(stderr, "%d: %s\n", mysql_errno(&mysql), mysql_error(&mysql));
}
else{
result = mysql_store_result(&mysql);
while((row = mysql_fetch_row(result))){
printf("%s : %s\n", row[0], row[1]);
}
mysql_free_result(result);
}
mysql_close(&mysql);
return 0;
}
makefile를 이용해서 컴파일 해 보도록 하겠습니다.
정상적으로 작동했다면 test라는 이름의 파일이 만들어 졌을 것입니다.
그 파일을 실행하죠..
소스를 보시면 아시겠지만 그리 어려운 부분은 없습니다.
참고 하시라고 몇가지 소스를 더 남겨 보겠습니다.
...
const char *sql_update =
"UPDATE table1 set col1 = 'text'
WHERE rec_id = '1000'";
... /* MySQL Initialization & Connection */
if(mysql_query(&mysql, sql_update))
{
fprintf(stderr, ...);
mysql_close(&mysql);
exit();
}
...
...
const char *sql_insert =
"INSERT INTO table1 (col1) VALUES (%s)";
char query[4096];
const char *colors[] = {"red", "yellow", "blue"};
uint nbr_colors = sizeof(colors)/sizeof(char *);
uint x;
... /* MySQL Initialization & Connection */
for(x = 1; x < nbr_colors; x++)
{
sprintf(query, sql_insert, colors[x]);
if(mysql_query(&mysql, query))
{
fprintf(stderr, "Could not insert row. %s %d: \%s \n",
query, mysql_errno(&mysql), mysql_error(&mysql));
mysql_close(&mysql);
exit();
}
printf("Row %d inserted \n", x);
...