错误处理
错误处理的两个函数:
// 返回错误码
unsigned int mysql_errno(MYSQL *connection);
// 返回错误详细信息
char* mysql_error(MYSQL *connection);
注意,当调用conn = mysql_real_connect(...), 时会遇到一个问题,因为它在失败时返回NULL指针,并没有提供一个错误码。但如果是将句柄作为一个变量,那么即使mysql_real_connect失败,也仍然能够处理它。
#include <stdio.h>
#include <stdlib.h>
#include "mysql.h"
#include "errmsg.h"
#include "mysqld_error.h"
void Error(MYSQL* conn) {
printf("Connection error %d: %s\n", mysql_errno(conn), mysql_error(conn));
}
int main (int argc, char *argv[]) {
MYSQL conn; // 是变量而不是指针
mysql_init(&conn); // 注意取地址符&
if (mysql_real_connect(&conn, "192.168.137.246", "root", "123456", "test", 0, NULL, 0)) {
printf("Connection success!\n");
mysql_close(&conn);
} else {
fprintf(stderr, "Connection failed!\n");
if (mysql_errno(&conn)) {
fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&conn), mysql_error(&conn));
}
}
return EXIT_SUCCESS;
}
