一、典型错误:
错误1:
命令:
gcc -I /usr/include/mysql/ -L /lib/-lmysqlclientmain.c
错误:
/tmp/ccT0KqUQ.o:main.c:(.text+0x2a): undefined reference to`mysql_init'
/tmp/ccT0KqUQ.o:main.c:(.text+0x2a): relocation truncated to fit:R_X86_64_PC32 against undefined symbol `mysql_init'
/usr/lib/gcc/x86_64-pc-cygwin/4.8.1/../../../../x86_64-pc-cygwin/bin/ld:/tmp/ccT0KqUQ.o: bad reloc address 0x0 in section `.pdata'
/usr/lib/gcc/x86_64-pc-cygwin/4.8.1/../../../../x86_64-pc-cygwin/bin/ld:final link failed: Invalid operation
collect2: error: ld returned 1 exit status
分析:
娘哎,我怎么会知道-I,-L,-l这些选项要放最后面呢???修改如下:
gcc main.c -I /usr/include/mysql/ -L /lib/ -lmysqlclient
错误2:
命令:
gcc main.c-I /usr/include/mysql/ -L /lib/-lmysqlclient
错误:
collect2: error: ld terminated with signal 11 [Segmentation fault],core dumped
分析:
估计你是自己从mysql.com下载的connector。抱歉,你得用cygwin提供的。方法如下:
1.打开cygwin的setup.exe,一路next,直到到达"select packages"页
2.搜索libmysql
3.打开DatabaseDefault节点,选择"libmysqlclient-devel","libmysqlclient18"。
4.安装
二、具体流程
1./root/src/test/main.c
[cpp]viewplaincopy- #include
- #include
- #include
- #include"mysql.h"
- voidhalt(MYSQL*,constchar*);
- intmain(intargc,char*argv[]){
- MYSQLmysql;
- //初始化mysql
- if(!mysql_init(&mysql))
- {
- halt(&mysql,"Mysqlinitfailed");
- }
- //连接
- if(!mysql_real_connect(&mysql,"127.0.0.1","root","123456","test",3306,"",0))
- {
- halt(&mysql,"Can'tconnecttomysqlserver");
- }
- //设置字符集
- if(0!=mysql_set_character_set(&mysql,"utf8")){
- halt(&mysql,"Can'tsetcharacter");
- }
- //查询test数据库的所有表
- constchar*sql="SHOWTABLES";
- if(0!=mysql_real_query(&mysql,sql,strlen(sql))){
- charmessage[200];
- sprintf(message,"QueryError:%s",sql);
- halt(&mysql,message);
- }
- //获得结果集
- MYSQL_RES*res=NULL;
- if(!(res=mysql_use_result(&mysql))){
- halt(&mysql,"Can'tfetchresult");
- }
- //输出结果
- MYSQL_ROWrow;
- while(row=mysql_fetch_row(res)){
- printf("table:%sn",row[0]);
- }
- //释放资源
- mysql_free_result(res);
- //关闭连接
- mysql_close(&mysql);
- return0;
- }
- voidhalt(MYSQL*mysql,constchar*message){
- fprintf(stderr,"message:%snerrno:%dnerror:%s",message,mysql_errno(mysql),mysql_error(mysql));
- exit(-1);
- }
gcc main.c -I /usr/include/mysql/ -L /lib/ -lmysqlclient
3.运行