|
ery_str = NULL; int rc, i, fields; int rows; if (NULL == mysql_init(&mysql)) { printf("mysql_init(): %s\n", mysql_error(&mysql)); return -1; } if (NULL == mysql_real_connect(&mysql, "localhost", "root", "shallnet", "db_users", 0, NULL, 0)) { printf("mysql_real_connect(): %s\n", mysql_error(&mysql)); return -1; } printf("1. Connected MySQL successful! \n"); //执行插入请求 query_str = "insert into tb_users values (12345, 'justtest', '2015-5-5')"; rc = mysql_real_query(&mysql, query_str, strlen(query_str)); if (0 != rc) { printf("mysql_real_query(): %s\n", mysql_error(&mysql)); return -1; } //执行删除请求 query_str = "delete from tb_users where userid=10006"; rc = mysql_real_query(&mysql, query_str, strlen(query_str)); if (0 != rc) { printf("mysql_real_query(): %s\n", mysql_error(&mysql)); return -1; } //然后查询插入删除之后的数据 query_str = "select * from tb_users"; rc = mysql_real_query(&mysql, query_str, strlen(query_str)); if (0 != rc) { printf("mysql_real_query(): %s\n", mysql_error(&mysql)); return -1; } res = mysql_store_result(&mysql); if (NULL == res) { printf("mysql_restore_result(): %s\n", mysql_error(&mysql)); return -1; } rows = mysql_num_rows(res); printf("The total rows is: %d\n", rows); fields = mysql_num_fields(res); printf("The total fields is: %d\n", fields); while ((row = mysql_fetch_row(res))) { for (i = 0; i < fields; i++) { printf("%s\t", row[i]); } printf("\n"); } mysql_free_result(res); mysql_close(&mysql); return 0; }
编译链接执行结果如下:
?
# make
cc -Wall -Werror -O2 -I/usr/include/mysql/ -c -o main.o main.c
Linking target_bin...
# ./target_bin
1. Connected MySQL successful!
The total rows is: 13
The total fields is: 3
10000 Allen 1981-01-01
10001 Ben 1982-04-02
10002 Curry 1985-08-12
10003 Davis 1978-07-12
10004 Ellis 1979-09-02
10005 Faried 1984-02-05
10007 Hamilton 1988-07-07
10008 Johnson 1986-06-07
10009 Jackson 1989-08-17
10010 James 1984-12-30
10011 Gay 1987-02-03
10012 Kaman 1981-04-04
12345 justtest 2015-05-05
?
|