我正在尝试在 Windows 8.1 上的 CodeBlocks 13.12 IDE 中使用 C 连接到 MySQL 服务器。以下是我的构建选项。
我的代码如下。
#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#pragma warning (disable: 4514 4786)
#pragma warning( push, 3 )
#endif
#include <stdio.h>
#include <mysql.h>
#ifndef WIN32
#include <unistd.h>
#endif
int main(int argc, char **argv)
{
MYSQL mysql;
if(mysql_init(&mysql)==NULL){
printf("\nFailed to initate MySQL connection");
exit(1);
}
/*now you can call any MySQL API function you like*/
if(!mysql_real_connect(&mysql,"localhost","user","password","molecules",0,NULL,0)){
printf( "Failed to connect to MySQL: Error: %s\n",
mysql_error(&mysql));
exit(1);
}
printf("Logged on to database sucessfully");
mysql_close(&mysql);
}
我收到以下错误。
有人可以帮我吗?
出于某种原因,Codeblocks 不喜欢 MySQL。我假设你有 MySQL C 连接器?如果没有,您可以在这里
获取它从 MySQL C Connector 目录中,复制名为 Include 的文件夹的完整内容,然后进入 MinGW 目录并将内容粘贴到 MinGW 的 Include 文件夹中。
下载this Zip 文件夹,其中包含 libmysql.a 和 libmysql.dll。解压libmysql.a并将其复制到MingGW的lib文件夹中。将 libmysql.dll 复制到 Windows System32 和 SysWOW64 文件夹中。
最后在 Codeblocks 中,在编译器设置/链接器设置/其他链接器选项中 - 键入“ -lmysql ”(不带引号)。
未在 Windows 8.1 上测试,适用于 Windows 7。
您有很多不必要的代码来测试连接。
#include <stdio.h>
#include <winsock2.h>
#include <mysql.h>
int main(int argc, char **argv)
{
MYSQL *conn = mysql_init(NULL);
if (!(mysql_real_connect(conn, "localhost", "username", "password", "database", 0, NULL, 0)))
{
printf(stderr, "%s\n", mysql_error(conn));
mysql_close(conn);
exit(1);
}
printf ("Connection Succesful");
mysql_close(conn);
return 0;
}
这解决了我的相同类型的编译/链接错误的问题。谢谢你。