我的C客户端程序连接MySQL服务器。我可以连接,但是当我尝试实现错误检测代码时会出现问题。如果我下面的(在这里我也故意把不正确的用户名):连接MySQL的C客户端程序中的错误检测
#include "mysql.h"
int main()
{
MYSQL* conn_ptr_db;
conn_ptr_db = mysql_init(NULL);
if(!conn_ptr_db)
{
perror("Error connecting to MySQL! ");
exit(0);
}
if(mysql_real_connect(conn_ptr_db,"localhost","rooti","root","mysql",0,NULL,0))
{
printf("Hurrah! we have connected to MySQL! ");
mysql_close(conn_ptr_db);
}
else
{
printf("Connection failed to MySQL! \n");
printf("Error code: %d %s %s\n",mysql_errno(conn_ptr_db),mysql_sqlstate(conn_ptr_db),mysql_error(conn_ptr_db));
}
//mysql_close(conn_ptr_db);
return 0;
}
现在输出到这个程序:
./db_access 连接失败到MySQL! 错误代码:1045 28000访问被拒绝用户'rooti'@'localhost'(使用密码:是)
这是正确的输出。
但是,如果我做到以下几点:
#include "mysql.h"
int main()
{
MYSQL* conn_ptr_db;
conn_ptr_db = mysql_init(NULL);
if(!conn_ptr_db)
{
perror("Error connecting to MySQL! ");
exit(0);
}
//CHANGES -------------
conn_ptr_db = mysql_real_connect(conn_ptr_db,"localhost","rooti","root","mysql",0,NULL,0);
if(conn_ptr_db)
{
printf("Hurrah! we have connected to MySQL! ");
mysql_close(conn_ptr_db);
}
else
{
printf("Connection failed to MySQL! \n");
printf("Error code: %d %s %s\n",mysql_errno(conn_ptr_db),mysql_sqlstate(conn_ptr_db),mysql_error(conn_ptr_db));
}
//mysql_close(conn_ptr_db);
return 0;
}
我得到以下输出: ./db_access 连接失败到MySQL! 错误代码:0 08001
在这里,mysql_errno()和mysql_error()不起作用。为什么?