我刚开始使用 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/