mysql - 为什么 mysql_query() 打印错误?

标签 mysql c api

我刚开始使用 C 和 MySQL C API。我正在使用 mysql_query() 创建一个表。根据 manual ,函数用法是 int mysql_query(MYSQL *mysql, const char *stmt_str),如果成功则函数返回 0,如果出错则返回非零。但是,无论我使用 if (mysql_query()) 还是 if ! (mysql_query()),程序总是打印到标准输出,“Error 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);
}

最佳答案

您只需在 if 语句的末尾放置一个分号 ;,这样大括号之间的代码就会始终执行!!!

去掉 ; 一切都会按预期工作

关于mysql - 为什么 mysql_query() 打印错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14410468/

相关文章:

javascript - 我如何将输入文本传递到 React 应用程序中的过滤器组件

javascript - Node.js 中的异步函数

c# - MySQL 参数化查询中的用户凭据无效

php不显示重复的id

android - 向内置相机应用程序发送命令

c++ - 传递给 main() 的 argc 和 argv 值是如何设置的?

c - 使用C linux在链表中进行哈希搜索

php - node.js 可以与 php 集成吗?

mysql - SQL 查询将我的数字返回为字符串而不是整数

无法 avformat_open_input .mp3