(1) Makefile
CC=gcc
CFLAGS=-Wall
INCLUDE=-I/usr/include/mysql
LDFLAGS=-L/usr/lib64/mysql -lmysqlclient
PROG=my_cnt
SRC=test_mysql.c
OBJS=$(patsubst %.c, %.o, $(SRC))
all: clean $(PROG)
clean:
rm -f $(PROG) *.o
$(OBJS): $(SRC)
$(CC) $(CFLAGS) $(INCLUDE) -c $<
$(PROG): $(SRC) $(OBJS)
$(CC) $(CFLAGS) $(OBJS) -o $(PROG) $(LDFLAGS)
(2)test_mysql.c
include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mysql.h"
void process_result_set(MYSQL *mysql, MYSQL_RES *result)
{
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("[%.*s] ", (int) lengths[i],
row[i] ? row[i] : "NULL");
}
printf("\n");
}
}
int main()
{
int status = 0;
int i = 0;
MYSQL m;
MYSQL *mysql = &m;
MYSQL_RES *result = NULL;
if (mysql_init(mysql) == NULL) {
printf("mysql init failed\n");
exit(1);
}
if (mysql_real_connect (mysql, host_name, user_name, password,
db_name, port_num, socket_name, CLIENT_MULTI_STATEMENTS) == NULL) {
printf("mysql_real_connect() failed\n");
mysql_close(mysql);
exit(1);
}
/* execute multiple statements */
status = mysql_query(mysql,
"CREATE TABLE if not exists test_table(id INT);\
INSERT INTO test_table VALUES(10);\
UPDATE test_table SET id=20 WHERE id=10;\
SELECT * FROM test_table;\
delete from test_table where id < 10;\
select count(*) from test_table");
if (status) {
printf("Could not execute statement(s)\n");
mysql_close(mysql);
exit(0);
}
/* process each statement result */
do {
/* did current statement return data? */
result = mysql_store_result(mysql);
if (result) {
/* yes; process rows and free the result set */
process_result_set(mysql, result);
mysql_free_result(result);
} else /* no result set or error */
{
if (mysql_field_count(mysql) == 0) {
printf("%lld rows affected\n", mysql_affected_rows(mysql));
} else /* some error occurred */
{
printf("Could not retrieve result set\n");
break;
}
}
/* more results? -1 = no, >0 = error, 0 = yes (keep looping) */
if ((status = mysql_next_result(mysql)) > 0)
printf("Could not execute statement\n");
printf("[%d]\n", ++i);
} while (status == 0);
mysql_close(mysql);
return 0;
}