//mysql_select//gcc mysql_select.c -o test -I /usr/include/mysql -L /usr/lib -lmysqlclient #include <stdio.h>#include <string.h>#include <mysql/mysql.
//mysql_select
//gcc mysql_select.c -o test -I /usr/include/mysql -L /usr/lib -lmysqlclient
#include <stdio.h>
#include <string.h>
#include <mysql/mysql.h>
#define HOST "localhost"
#define USERNAME "SERVER"
#define PASSWORD "SERVER_PASSWORD"
#define DATABASE "remote_control"
int main()
{
//char *sql = "select * from devices";
char *sql = "select * from users";
int res;
int i, j;
int row, column;/*查詢返回的行數和列數*/
MYSQL my_connection;
MYSQL_RES *res_ptr;/*指向查詢結果的指針*/
MYSQL_FIELD *field;/*欄位結構指針*/
MYSQL_ROW result_row;/*按行返回的查詢信息*/
mysql_init(&my_connection);/*初始化mysql連接my_connection*/
if (!mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD, DATABASE, 3306, NULL, CLIENT_FOUND_ROWS))
{/*連接失敗*/
printf("資料庫連接失敗: %s\n", mysql_error(&my_connection));
return 0;
}
mysql_query(&my_connection, "set names utf8");/*設置編碼為utf8*/
res = mysql_real_query(&my_connection, sql, (unsigned int)strlen(sql));
if (res)
{/*執行失敗*/
printf("sql語句執行失敗: %s\n", mysql_error(&my_connection));
mysql_close(&my_connection);
return 0;
}
res_ptr = mysql_store_result(&my_connection);/*將查詢的結果給res_ptr*/
if (!res_ptr)
{
printf("查詢結果為空\n");
mysql_close(&my_connection);
return 0;
}
column = mysql_num_fields(res_ptr);/*取得結果的列數和*/
row = mysql_num_rows(res_ptr);/*取得結果的行數和*/
printf("查詢到 %d 行\n", row);
for (i = 0; field = mysql_fetch_field(res_ptr); i++)/*輸出結果的欄位名*/
printf("%s ", field->name);
printf("\n");
for (i = 0; i < row; i++)/*按行輸出結果*/
{
result_row = mysql_fetch_row(res_ptr);
for (j = 0; j < column; j++)
printf("%s ", result_row[j]);
printf("\n");
}
mysql_free_result(res_ptr);
mysql_close(&my_connection);
return 0;
}