C language connection mysql -- select Code implementation, C language mysqlselect
// 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;/* query the number of returned rows and columns */
MYSQL my_connection;
MYSQL_RES * res_ptr;/* pointer to the query result */
MYSQL_FIELD * field;/* field structure pointer */
MYSQL_ROW result_row;/* query information returned by row */
Mysql_init (& my_connection);/* initialize mysql connection my_connection */
If (! Mysql_real_connect (& my_connection, HOST, USERNAME, PASSWORD, DATABASE, 3306, NULL, CLIENT_FOUND_ROWS ))
{/* Connection Failed */
Printf ("Database Connection Failed: % s \ n", mysql_error (& my_connection ));
Return 0;
}
Mysql_query (& my_connection, "set names utf8");/* set the encoding to utf8 */
Res = mysql_real_query (& my_connection, SQL, (unsigned int) strlen (SQL ));
If (res)
{/* Execution failed */
Printf ("SQL statement execution failed: % s \ n", mysql_error (& my_connection ));
Mysql_close (& my_connection );
Return 0;
}
Res_ptr = mysql_store_result (& my_connection);/* Send the query result to res_ptr */
If (! Res_ptr)
{
Printf ("the query result is blank \ n ");
Mysql_close (& my_connection );
Return 0;
}
Column = mysql_num_fields (res_ptr);/* Number of columns and */
Row = mysql_num_rows (res_ptr);/* The number of rows and */
Printf ("% d row \ n", row );
For (I = 0; field = mysql_fetch_field (res_ptr); I ++)/* Name of the output field */
Printf ("% s", field-> name );
Printf ("\ n ");
For (I = 0; I <row; I ++)/* result output by line */
{
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;
}