#include #include #include #include /* Perform operations on the below table in mariadb. CREATE TABLE `person` ( `id` INTEGER PRIMARY KEY, `name` TEXT); INSERT INTO `person` VALUES(1, 'name1'), (2, 'name2'); */ #define DB_CONN_STR "127.0.0.1" #define DB_CONN_USER "root" #define DB_CONN_PWD "" #define DB_NAME "test" /* For demo only, so little error handling is done. */ int main(void) { unsigned int timeout = 2; MYSQL* conn = mysql_init(NULL); mysql_options(conn, MYSQL_OPT_CONNECT_TIMEOUT, &timeout); if (mysql_real_connect(conn, DB_CONN_STR, DB_CONN_USER, DB_CONN_PWD, DB_NAME, 0, NULL, 0) == NULL) { perror("db connect failed.\n"); return 1; } MYSQL_STMT* stmt1 = mysql_stmt_init(conn); MYSQL_STMT* stmt2 = mysql_stmt_init(conn); /* Query statement of stmt1 can be any statement. If it is a statement with one or more result sets, all result sets must be fetched or stored after the execution is completed so that the next statement can be successfully executed without command sync error(2014). */ mysql_stmt_prepare(stmt1, "SET @a = 1", (unsigned long)-1); mysql_stmt_prepare(stmt2, "SELECT * FROM `person`", (unsigned long)-1); if (mysql_stmt_execute(stmt1) == 0) { // stmt1 complete and no result set, so we can happy to execute next query. int res = mysql_stmt_execute(stmt2); printf("Stmt2: %s\n", res ? "Execution Failed" : "Execution Succeed"); printf("Field of stmt2 result set: %u\n", mysql_stmt_field_count(stmt2)); /* Without exception, the previous execution will complete successfully. We ***close stmt1 before getting result set of stmt2 ***. */ mysql_stmt_close(stmt1); stmt1 = NULL; /* Now we stored result set of stmt2. In theory it should succeed and the closing of stmt1 which has done work should be independent of stmt2. But the reality is that the following statement is bound to fail. */ if (mysql_stmt_store_result(stmt2)) { /***************************************************** *** Oops!!! the result set of stmt2 disappeared. *** We can only get the following errors: "Commands out of sync; you can't run this command now: No error" If we change mysql_execute(stmt2) to mysql_query(conn, ...), same problem exists. *****************************************************/ perror(mysql_stmt_error(stmt2)); perror("\n"); } } if (stmt1) mysql_stmt_close(stmt1); if (stmt2) mysql_stmt_close(stmt2); mysql_close(conn); return 0; }