/1.cc
Created
June 13, 2020 11:06
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// g++ -I/usr/local/mysql/include/mysql -L/usr/local/mysql/lib/ 1.cc -lmysqlclient | |
// export LD_LIBRARY_PATH=/usr/local/mysql/lib/ | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <mysql.h> | |
int run_mysql_query(MYSQL *mysql, const char *query) | |
{ | |
int rc= mysql_query(mysql, query); | |
if (!rc) | |
printf("%s OK\n", query); | |
else | |
printf("%s FAILED\n", query); | |
return rc; | |
} | |
int main(int args, char **argv) | |
{ | |
MYSQL *lmysql; | |
lmysql= mysql_init(NULL); | |
MYSQL *res= mysql_real_connect(lmysql, "127.0.0.1", "root", | |
NULL, "test", 3319, | |
NULL, 0); | |
if (!res) { | |
puts("Failed to connect"); | |
exit(1); | |
} | |
int rc; | |
if (run_mysql_query(lmysql, "drop table if exists t1")) | |
exit(1); | |
if (run_mysql_query(lmysql, "create table t1(a int, b int, key(a))")) | |
exit(1); | |
if (run_mysql_query(lmysql, "insert into t1 (a) values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);")) | |
exit(1); | |
MYSQL_STMT *stmt= mysql_stmt_init(lmysql); | |
if (!stmt) { | |
puts("Failed to init stmt"); | |
exit(1); | |
} | |
const char* query= | |
"explain " | |
"with T as " | |
"( " | |
" select * from t1 where t1.a=? limit 2 " | |
") " | |
"select * from T as TA, T as TB;"; | |
rc= mysql_stmt_prepare(stmt, query, (uint) strlen(query)); | |
if (rc) { | |
puts("mysql_stmt_prepare failed"); | |
exit(1); | |
} | |
puts("Statement prepared"); | |
MYSQL_BIND ps_params[1]; | |
int int_data[1]; | |
int_data[0]=2; | |
ps_params[0].buffer_type= MYSQL_TYPE_LONG; | |
ps_params[0].buffer= (char *) &int_data[0]; | |
ps_params[0].length= 0; | |
ps_params[0].is_null= 0; | |
rc= mysql_stmt_bind_param(stmt, ps_params); | |
if (rc) { | |
puts("mysql_stmt_bind_param failed"); | |
exit(1); | |
} | |
/// | |
rc= mysql_stmt_execute(stmt); | |
if (rc) { | |
puts("mysql_stmt_execute failed"); | |
exit(1); | |
} | |
puts("Statement Executed"); | |
if (mysql_stmt_store_result(stmt)) | |
puts("mysql_stmt_store_result failed"); | |
int affected_rows= mysql_stmt_num_rows(stmt); | |
printf("%d rows.\n", affected_rows); | |
/// | |
rc= mysql_stmt_execute(stmt); | |
if (rc) { | |
puts("mysql_stmt_execute 2 failed"); | |
exit(1); | |
} | |
puts("Statement Executed 2 "); | |
if (mysql_stmt_store_result(stmt)) | |
puts("mysql_stmt_store_result 2 failed"); | |
affected_rows= mysql_stmt_num_rows(stmt); | |
printf("%d rows. 2\n", affected_rows); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment