测试环境:CentOS 5.4 64位 mysql5.5.20
mysql使用bin安装,安装在/program/mysql目录
代码
#include
#include
#include
#define GET_ARRAY_LEN(array,len) {len = (sizeof(array) / sizeof(array[0]));}
int main(int argc,char **argv )
{
MYSQL *sql_p;
MYSQL_RES *result_p;
MYSQL_ROW row_p;
int res;
int len;
sql_p=mysql_init(NULL);
if(sql_p==NULL){
printf("Init error!\n");
exit(1);
}
sql_p=mysql_real_connect(sql_p,"192.168.1.41","root","test",
"mysql",0,NULL,0);
if(!sql_p){
fprintf(stderr,"%d:%s\n",mysql_errno(sql_p),mysql_error(sql_p));
exit(1);
}
res=mysql_query(sql_p,"SELECT * FROM admin");
if(res){
printf("Select error!\n");
exit(1);
}
result_p=mysql_use_result(sql_p);
if(!result_p){
printf("mysql_use error!\n");
exit(1);
}
row_p=mysql_fetch_row(result_p);
GET_ARRAY_LEN(row_p,len);
printf("%d\n",len);
int i;
for (i=0 ;i<20 ;i++)
{if (row_p[i][1])
printf("%s\n",row_p[i]);
}
mysql_close(sql_p);
return 0;
}
编译语句
gcc -Wall cmysql.c -o cmysql -L /program/mysql/lib -I /program/mysql/include/ -lmysqlclient -lz
问题:
运行报错
./cmysql: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: No such file or directory
解决办法:
32位操作系统运行下面一句
ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib/
64位操作系统运行下面一句
ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib64/
再次编译通过。
在读取数据时还出现一个问题,如果没有数据,程序显示错误,这个我没有处理。