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