c/c++-使用 mysql c api 中,预处理查询条件 当过滤字段是字符串时
程序员文章站
2022-06-11 15:34:18
...
mysqlc/c++
#include #include #include int main(void){ // declares MYSQL * connection = NULL; MYSQL_STMT * stmt = NULL; MYSQL_BIND bind[3]; MYSQL_BIND inbind; // preprocess bzero(bind, sizeof(bind)); bzero(&inbind, sizeof(inbind)); // declare MYSQL * ptr connection = mysql_init(NULL); if (NULL == connection) { fprintf(stderr, "mysql_init err!"); return -1; } // connect connection = mysql_real_connect(connection, "localhost", "root", "root", "dblinuxcmysqlctr", 0, NULL, 0); if (NULL == connection) { fprintf(stderr, "mysql_real_connect err!"); return -1; } /* 1. init */ stmt = mysql_stmt_init(connection); /* ******************************************************** */ //char * insertsql = "select name from tlinuxcmysqlctr where age = ?;"; // 这里不就可以过滤了,过滤出来没有数据,是为啥呀? char * insertsql = "select name from tlinuxcmysqlctr where name = ?;"; /* ******************************************************** */ /* 2. prepare */ if(mysql_stmt_prepare(stmt, insertsql, strlen(insertsql))) { printf("mysql_stmt_prepare err!\n"); return -1; } char inpara1[50] = {0}; //int inpara1 = 4; char outpara1[50] = {0}; //bind[0].buffer_type = MYSQL_TYPE_LONG; //bind[0].buffer = &inpara1; //bind[0].buffer_length = sizeof(inpara1); bind[0].buffer_type = MYSQL_TYPE_STRING; strcpy(inpara1, "hello"); bind[0].buffer = inpara1; bind[0].buffer_length = sizeof(inpara1); bind[1].buffer_type = MYSQL_TYPE_STRING; bind[1].buffer = outpara1; bind[1].buffer_length = 50; /* 3. bind_param */ mysql_stmt_bind_param(stmt, bind + 0); /* 4. execute */ if (mysql_stmt_execute(stmt)) { printf("sorry\n"); } else { /* 3.5 */ mysql_stmt_bind_result(stmt, bind + 1); printf("bind[0].buffer = %s\n", (char *)bind[0].buffer); if (0 != mysql_stmt_store_result(stmt)) { printf("store result stmt err\n"); return -1; } else { printf("----------------------------table data--------------------------------\n"); while (!mysql_stmt_fetch(stmt)) { printf("name = %s\n", outpara1); } } mysql_stmt_free_result(stmt); } /* 5. close */ mysql_stmt_close(stmt); // mysql_close mysql_close(connection); return 0;}