#include <stdlib.h>
#include <stdio.h>
#include <mysql/mysql.h>
int main(void){
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;
MYSQL *conn_ptr;
int result;//query result
int iTableRow,iTableCol,i,j;
conn_ptr = mysql_init(NULL);
if (!conn_ptr)
{
fprintf(stderr,"mysql_init failed!\n");
return (-1);
}
conn_ptr = mysql_real_connect(conn_ptr,"127.0.0.1","root","123456","mysql",3306,0,NULL);
if (conn_ptr)
{
printf ("connection succeed!\n");
}
else{
printf ("connection failed!\n");
return (-2);
}
result = mysql_query(conn_ptr,"select * from test.tbl_user");
if(result){
printf(stderr,"select error %d: %s !\n",mysql_errno(conn_ptr),mysql_error(conn_ptr));//
return EXIT_FAILURE;
}
res_ptr = mysql_store_result(conn_ptr);//集合
if( res_ptr )
{
iTableRow = mysql_num_rows(res_ptr);//行
iTableCol = mysql_num_fields(res_ptr);//列
for(i=0; i<iTableRow; i++)
{
sqlrow = mysql_fetch_row(res_ptr);
for(j=0; j<iTableCol; j++)
{
printf("%-8s ",sqlrow[j]);//字符串向左靠,右补空格
}
printf("\n");
}
mysql_free_result(res_ptr);//完成对数据的所有操作后,调用此函数来让MySQL库清理它分配的对象
mysql_close(conn_ptr);
printf ("connection close!\n");
return 0;
}
编译:gcc -o mydbcon -I /usr/include/mysql/ -L /usr/lib/mysql -lmysqlclient mysql.c
运行:./mydbcon