最近应用集成大作业,刚好需要用到c++连接mysql,顺便学习下,记录一些内容概要,以便将来复习。
mysql的header files :头文件在.../MySQL/MySQL Server 5.1/include下。
mysql的client library :库文件在...MySQL/MySQL Server 5.1/lib/opt下。
新建工程,设置additional include directories,包含需要的库的目录
当然,也可以不需要这样设置,不过包含头文件时候应该显示指明路径:
#include "C:/Program Files/MySQL/MySQL Server 5.1/include/mysql.h"
然后包含需要的lib,当然可以使用
#pragma comment(lib,"your_additional_lib_path")
不过对整个工程设置下也不错:
然后简单用c代码测试了一下(参照了《MySQL™ The definitive guide to using, programming, and administering MySQL 》)
#include <stdlib.h>
#include <stdio.h>
#include <WinSock2.h>
#include "mysql.h"
static char *opt_host_name = "localhost";
static char *opt_user_name = "root";
static char *opt_password = "Napoleon073218";
static unsigned int opt_port_num = 0; /*using built-in value*/
static char *opt_socket_name = NULL; /*using built-in value*/
static char *opt_db_name = NULL;
static unsigned int opt_flags = 0;
static MYSQL *cont; /*pointer to connection handler*/
int main() {
/*initialize connection handler*/
cont = mysql_init(NULL);
if (cont == NULL) {
fprintf(stderr, "mysql_init() falied (probably out of memory)/n");
exit(1);
}
/*connect to server*/
if (mysql_real_connect(cont, opt_host_name, opt_user_name, opt_password,
opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL) {
unsigned int err_no = mysql_errno(cont);
const char *err_str = mysql_error(cont);
fprintf(stderr, "mysql_real_connect() failed, error code %d: %s/n", err_no, err_str);
exit(1);
}
/*connected to the server, begin to process the data*/
printf("great, connected from the mysql server.../n");
/*disconnect from server*/
mysql_close(cont);
return 0;
}
写好完成,赶紧编译,结果link时候报错,我纠结啊,又把opt目录下的libmysql.dll复制到当前目录下,不可以。
转而一想,我的MySQL是64位的,dll文件也该是64位的,默认设置是debug模式下win32,赶紧换成debug模式下的x64,编译,结果不报link找不到类似的错误。
但是有fatal error LNK1107: invalid or corrupt file: cannot read at 0x308
没办法,猜测可能debug模式下加入了了过多的信息,修改为release模式下的x64平台,编译通过。
设置编译为c程序。
运行,成功了,心里很安慰啊。
折腾了不少时间。赶紧睡觉咯。
明天辅修课上继续折腾吧。