39 lines
1.1 KiB
C
39 lines
1.1 KiB
C
#include "mysql.h"
|
|
|
|
int _mysql(char *sql, char *MYSQL_HOST, char *MYSQL_PORT_, char *MYSQL_USRT, char *MYSQL_PASSWORD, char *MYSQL_DB, char *MYSQL_TABLES)
|
|
{
|
|
static MYSQL mysql; // 静态变量,仅初始化一次
|
|
static char MYSQL_DB_[270] = { 0 };
|
|
|
|
if (!mysql_init(&mysql)) {
|
|
perror("mysql_init");
|
|
return -1;
|
|
}
|
|
|
|
int result = 0;
|
|
|
|
if (mysql_real_connect(&mysql, MYSQL_HOST, MYSQL_USRT, MYSQL_PASSWORD, "mysql", atoi(MYSQL_PORT_), NULL, 0)) {
|
|
if (0 != mysql_set_character_set(&mysql, "utf8")) {
|
|
perror("mysql_set_character_set");
|
|
result = -1;
|
|
goto shutdown;
|
|
}
|
|
|
|
sprintf(MYSQL_DB_, "use %s;", MYSQL_DB);
|
|
if (mysql_query(&mysql, MYSQL_DB_) || mysql_query(&mysql, sql)) {
|
|
fprintf(stderr, "Query execution failed: %s\n", mysql_error(&mysql));
|
|
result = -1;
|
|
} else {
|
|
// 执行成功的操作
|
|
}
|
|
} else {
|
|
fprintf(stderr, "Connect failed: %s\n", mysql_error(&mysql));
|
|
result = -1;
|
|
}
|
|
|
|
shutdown:
|
|
mysql_close(&mysql);
|
|
|
|
return result;
|
|
}
|