http://www.erickcantwell.com/2011/08/mysql-prepared-statements-in-c/
[root@li408-34 mysql]# cat a.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <mysql/mysql.h> #define STRING_SIZE 256 int main() { MYSQL *mysql; MYSQL_STMT *stmt; MYSQL_BIND param[1], result[1]; char *sql; mysql = mysql_init(NULL); /* Here we make the connection to MySQL */ if (mysql_real_connect(mysql, "localhost", "root", "haoning", "test", 0, NULL, 0) == NULL) { fprintf(stderr, "No connection could be made to the database\n"); exit(EXIT_FAILURE); } sql = "SELECT `name` FROM `mytest` WHERE `name` = ?"; int param_count; short small_data; int int_data; char str_data[STRING_SIZE]; char result_data[STRING_SIZE]; unsigned long str_length; unsigned long data_length; my_bool is_null; /* Initialize our statement */ stmt = mysql_stmt_init(mysql); if (!stmt) { fprintf(stderr, " mysql_stmt_init(), out of memory\n"); exit(EXIT_FAILURE); } if (mysql_stmt_prepare(stmt, sql, strlen(sql))) { fprintf(stderr, " mysql_stmt_prepare(), INSERT failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } /* Zero out both the param and result data structures */ memset(param, 0, sizeof(param)); memset(result, 0, sizeof(result)); /* STRING PARAM */ param[0].buffer_type = MYSQL_TYPE_STRING; param[0].buffer = (char *)str_data; param[0].buffer_length = STRING_SIZE; param[0].is_null = 0; param[0].length = &str_length; result[0].buffer_type= MYSQL_TYPE_VAR_STRING; result[0].buffer = result_data; result[0].buffer_length = STRING_SIZE; result[0].is_null = 0; result[0].length = &data_length; /* Bind the parameters buffer */ if (mysql_stmt_bind_param(stmt, param)) { fprintf(stderr, " mysql_stmt_bind_param() failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } /* Bind the results buffer */ if (mysql_stmt_bind_result(stmt, result) != 0) { fprintf(stderr, " mysql_stmt_bind_result() failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } /* Specify the parameter that we send to the query */ strncpy(str_data, "haha1", STRING_SIZE); str_length= strlen(str_data); /* Execute the statement */ if (mysql_stmt_execute(stmt)) { fprintf(stderr, " mysql_stmt_execute(), failed\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } /* Print our results */ if(mysql_stmt_fetch (stmt) == 0) { printf("%s\n", result_data); } else { printf("No results found!\n"); } /* Close the statement */ if (mysql_stmt_close(stmt)) { fprintf(stderr, " failed while closing the statement\n"); fprintf(stderr, " %s\n", mysql_stmt_error(stmt)); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
[root@li408-34 mysql]# cat make.sh #!/bin/sh #gcc -Wall -L /usr/lib/mysql/ -l mysqlclient mysql_query.c -o mysql_query.o -g gcc -Wall -L /usr/lib/mysql/ -l mysqlclient a.c -o mysql_query.o -g