我的C客户端程序与MySQL服务器连接。我可以连接,但是当我尝试实现错误检测代码时,问题就出现了。如果我做了以下事情(在这里我故意输入了错误的用户名):
#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_ MySQL连接失败!错误代码: 1045 28000拒绝访问用户'rooti'@'localhost‘(使用密码: YES)
这是正确的输出。
但如果我执行以下操作:
#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 Connection to MySQL!错误码:0 08001
在这里,mysql_errno()和mysql_error()不起作用。为什么?
发布于 2011-06-13 22:17:38
连接失败后,conn_ptr_db设置为NULL。然后尝试将该值用作调用msql_errono()的参数,实际上是msql_errno(NULL)。因此,您得到的错误代码。
发布于 2011-06-13 22:24:06
因为在第二个示例中,您将结果赋给了conn_ptr_db。
你不应该这样做。
如果连接成功,则为MYSQL*连接句柄;如果连接不成功,则为NULL。如果连接成功,则返回值与第一个参数的值相同。
在连接不成功的情况下(您已经有了),您已经用NULL替换了conn_ptr_db对象,然后尝试使用它(mysql_error)。
The documentation for mysql_error并没有明确表示不允许使用NULL参数,但是很明显,您不会得到与您所覆盖的原始实际连接上下文相关的错误。
https://stackoverflow.com/questions/6331481
复制相似问题