为什么mysql_query()会输出错误?

时间:2013-01-19 02:11:35

标签: mysql c api

我刚开始使用C和MySQL C API。我正在使用mysql_query()来创建一个表。根据{{​​3}},函数用法为int mysql_query(MYSQL *mysql, const char *stmt_str),如果成功则返回0,出错时返回非零值。但是,无论我使用if (mysql_query())还是if ! (mysql_query()),程序始终打印到stdout,“错误0:”。此外,在任何一种情况下,程序都会创建数据库和表。

#include <my_global.h>
#include <mysql.h>

int main (int argc, char **argv)
{
    MYSQL *connection;

    const char DATABASE[] = "test";
    const char HOSTNAME[] = "localhost";
    const char USERNAME[] = "root";
    const char PASSWORD[] = "123456";

    connection = mysql_init(NULL);

    if (connection == NULL)
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_real_connect(connection, HOSTNAME, USERNAME, PASSWORD, NULL, 0, NULL, 0) == NULL)
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_query(connection, "DROP DATABASE IF EXISTS test"))
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_query(connection, "CREATE DATABASE test"))
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    if (mysql_select_db(connection, DATABASE))
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    /* The problem that I do not understand is happening in the statement below.
     * It seems that a successful query returns zero, so I should not see "Error 0:"
     */
    if (mysql_query(connection, "CREATE TABLE jobs (id int(11) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, PRIMARY KEY (id), UNIQUE KEY name_index (name)) ENGINE=InnoDB DEFAULT CHARSET=utf8"));
    {
        printf("Error %u: %s\n", mysql_errno(connection), mysql_error(connection));
        exit(1);
    }

    mysql_close(connection);
}

2 个答案:

答案 0 :(得分:1)

您只需在 if 语句的末尾添加分号; ,以便大括号之间的代码始终执行!!!

取走; ,一切都会按预期运作

答案 1 :(得分:0)

这从手册页中并不完全清楚,但我的猜测是该函数的返回码是错误代码。因此,您必须在变量中捕获该返回值,然后在出现错误时打印该变量的值。