cygwin下用mysql c api连接数据库详解

一、典型错误:

错误1:

命令:

gcc -I /usr/include/mysql/ -L /lib/ -lmysqlclient main.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.打开Database Default节点,选择"libmysqlclient-devel","libmysqlclient18"。

4.安装

二、具体流程

1./root/src/test/main.c

 

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include "mysql.h"



void halt(MYSQL*, const char*);



int main(int argc, char*argv[]) {

    

    MYSQL mysql;

    

    //初始化mysql

    if(!mysql_init(&mysql))

    {

        halt(&mysql, "Mysql init failed");

    }

    

    //连接

    if(!mysql_real_connect(&mysql, "127.0.0.1", "root", "123456", "test", 3306, "", 0))

    {

       halt(&mysql, "Can't connect to mysql server");

    }

    

    //设置字符集

    if(0 != mysql_set_character_set(&mysql, "utf8")) {

        halt(&mysql, "Can't set character");

    }

    

    //查询test数据库的所有表

    const char* sql = "SHOW TABLES";

    if(0 != mysql_real_query(&mysql, sql, strlen(sql))) {

        char message[200];

        sprintf(message, "Query Error:%s", sql);

        halt(&mysql, message);

    }

    

    //获得结果集

    MYSQL_RES* res = NULL;

    if(!(res = mysql_use_result(&mysql))) {

        halt(&mysql, "Can't fetch result");

    }

    

    //输出结果

    MYSQL_ROW row;

    while(row = mysql_fetch_row(res)) {

        printf("table:%s\n", row[0]);

    }

    

    //释放资源

    mysql_free_result(res);

    

    //关闭连接

    mysql_close(&mysql);



    return 0;

}



void halt(MYSQL* mysql, const char* message) {

    fprintf(stderr, "message: %s\nerrno:%d\nerror:%s", message, mysql_errno(mysql), mysql_error(mysql));

    exit(-1);

}

2.编译&链接

 

gcc main.c -I /usr/include/mysql/ -L /lib/ -lmysqlclient

3.运行

 

你可能感兴趣的:(cygwin)