#include "stdio.h" #include "stdlib.h" #include "string.h" #include int exit_failure(const char *msg, MYSQL *mysql, MYSQL_RES *res, MYSQL_STMT *stmt); int main(void) { const char* sql_select = "SELECT 1, 'a'"; MYSQL *conn; MYSQL_STMT *stmt; MYSQL_RES *res; MYSQL_ROW row; MYSQL_FIELD *column; my_bool attr_get; unsigned int i, num_fields; int ret; conn = mysql_init(NULL); if (conn == NULL) exit_failure("mysql_init() failed", NULL, NULL, NULL); if (!mysql_real_connect(conn, "localhost", "root", "root", "phptest", 0, "/tmp/mysql.sock", 0)) exit_failure("mysql_real_connect() failed", conn, NULL, NULL); printf("%s...\n\n", sql_select); stmt = mysql_stmt_init(conn); if (mysql_stmt_prepare(stmt, sql_select, strlen(sql_select))) exit_failure("mysql_stmt_prepare() failed", conn, NULL, stmt); if (mysql_stmt_execute(stmt)) exit_failure("mysql_stmt_execute() failed", conn, NULL, stmt); if (res = mysql_store_result(conn)) printf("... can create a result set from the connection!\n"); printf("... result metadata from the connection\n"); for (i = 0; i < mysql_num_fields(res); i++) { column = mysql_fetch_field_direct(res, i); printf("\tColumn %d - type = %lu\n", i, column->type); printf("\tColumn %d - length = %lu\n", i, column->length); printf("\tColumn %d - max_length = %lu\n", i, column->max_length); } printf("\n"); printf("... and how about data?\n"); num_fields = mysql_num_fields(res); while (row = mysql_fetch_row(res)) { unsigned long *lengths; lengths = mysql_fetch_lengths(res); for(i = 0; i < num_fields; i++) { printf("\tField %d -> '%.*s'\n", i, (int) lengths[i], row[i] ? row[i] : "NULL"); } printf("\n"); } printf("\n"); mysql_free_result(res); mysql_stmt_close(stmt); mysql_close(conn); return EXIT_SUCCESS; } int exit_failure(const char *msg, MYSQL *mysql, MYSQL_RES *res, MYSQL_STMT *stmt) { printf("ERROR: %s\n", msg); if (stmt) { printf("[%u] %s\n", mysql_stmt_errno(stmt), mysql_stmt_error(stmt)); mysql_stmt_close(stmt); } if (mysql) { if (mysql_errno(mysql)) printf("[%u] %s\n", mysql_errno(mysql), mysql_error(mysql)); if (res) mysql_free_result(res); mysql_close(mysql); } printf("\n"); exit(EXIT_FAILURE); }