#include <mysql.h>
#include <stdio.h>
#include <string.h>

#if (MYSQL_VERSION_ID > 80000) && (MYSQL_VERSION_ID < 100000)
typedef bool my_bool;
#endif

int main()
{
  MYSQL *mysql, *conn;
  MYSQL_RES *result;
  MYSQL_ROW row;
  MYSQL_STMT *stmt;
  MYSQL_BIND bind[1];
  char str_data[20];
  my_bool is_null;
  my_bool error;
  unsigned long length;

  mysql = mysql_init(NULL);

#if (MYSQL_VERSION_ID > 80000) && (MYSQL_VERSION_ID < 100000)
  conn = mysql_real_connect(mysql, "127.0.0.1", "msandbox", "msandbox",
                            "test", 8013, NULL, 0);
#else
  conn = mysql_real_connect(mysql, "127.0.0.1", "msandbox", "msandbox",
                            "test", 10311, NULL, 0);
#endif

  if (conn == NULL)
  {
    printf("Failed to connect: %s\n", mysql_error(mysql));
    return 1;
  }

  printf("Client compile version: %d\n", MYSQL_VERSION_ID);
  printf("Client runtime version: %s\n", mysql_get_client_info());
  printf("Server version: %lu\n", mysql_get_server_version(mysql));

  mysql_query(mysql, "DROP TABLE IF EXISTS t");
  mysql_query(mysql, "CREATE TEMPORARY TABLE t(id smallint(5) unsigned zerofill)");
  mysql_query(mysql, "INSERT INTO t(id) VALUES(1)");
  mysql_query(mysql, "SELECT id FROM t");
  result = mysql_store_result(mysql);
  mysql_free_result(result); 
  row = mysql_fetch_row(result);
  printf("Result: %s\n", row[0]);

  stmt = mysql_stmt_init(mysql);
  mysql_stmt_prepare(stmt, "DROP TABLE IF EXISTS t", 22);
  mysql_stmt_execute(stmt);
  mysql_stmt_prepare(stmt, "CREATE TEMPORARY TABLE t(id smallint(5) unsigned zerofill)", 58);
  mysql_stmt_execute(stmt);
  mysql_stmt_prepare(stmt, "INSERT INTO t(id) VALUES(1)", 27);
  mysql_stmt_execute(stmt);

  for (int i = 1; i <= 5; i++) {
    printf("\nBuffer length: %d\n", i);
    mysql_stmt_prepare(stmt, "SELECT id FROM t", 16);
    mysql_stmt_execute(stmt);

    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type= MYSQL_TYPE_STRING;
    bind[0].buffer= (char *)str_data;
    bind[0].buffer_length= i;
    bind[0].is_null= &is_null;
    bind[0].length= &length;
    bind[0].error= &error;

    mysql_stmt_bind_result(stmt, bind);
    mysql_stmt_store_result(stmt);
    int fetch_result = mysql_stmt_fetch(stmt);
    printf("mysql_stmt_fetch result: %d\n", fetch_result);

    printf("Result: %s (prepared statement)\n", str_data);
  }
  mysql_stmt_close(stmt);
  mysql_close(mysql);
}
