2025-02-06 22:43:19 +08:00

108 lines
2.4 KiB
C

#ifndef MYSQL_H
#include <mysql.h>
#endif
#ifndef STDIO_H
#include <stdio.h>
#endif
#ifndef STDLIB_H
#include <stdlib.h>
#endif
#ifndef STRING_H
#include <string.h>
#endif
//对MySQL连接指针变量 创建结构体变量并取别名
typedef struct {
MYSQL *conn;
} DBConnection;
DBConnection *db_init(const char *host, const char *user, const char *password, const char *database, unsigned int port) {
//动态内存分配连接的地址
DBConnection *db = (DBConnection *)malloc(sizeof(DBConnection));
if (db == NULL) {
printf("内存分配错误\n");
return NULL;
}
//对连接地址进行动态内存分配
db->conn = mysql_init(NULL);
if (db->conn == NULL) {
printf("初始化失败\n");
free(db);
return NULL;
}
//对连接地址进行配置
if (mysql_real_connect(db->conn, host, user, password, database, port, NULL, 0) == NULL) {
printf("配置连接失败: %s\n", mysql_error(db->conn));
mysql_close(db->conn);
free(db);
return NULL;
}
mysql_set_character_set(db->conn, "GBK");//设置输入输出结果字符串为GBK
return db;
}
//关闭连接函数
void db_close(DBConnection *db) {
if (db != NULL) {
if (db->conn != NULL) {
mysql_close(db->conn);
}
free(db);
}
}
//更新、删除、新增 通用函数
int db_common(DBConnection *db, const char *query) {
if (mysql_query(db->conn, query)) {
printf("common query failed: %s\n", mysql_error(db->conn));
return 0;
}
if (strncmp(query, "INSERT", 6) == 0) {
return (int)mysql_insert_id(db->conn);
}
return (int)mysql_affected_rows(db->conn);
}
//查询通用函数
MYSQL_RES *db_query(DBConnection *db, const char *query) {
MYSQL_RES *result;
if (mysql_query(db->conn, query)) {
printf("查询失败: %s\n", mysql_error(db->conn));
return NULL;
}
result = mysql_store_result(db->conn);
if (result == NULL) {
printf("获取查询结果失败: %s\n", mysql_error(db->conn));
}
return result;
}
//处理查询结果函数
void process_result(MYSQL_RES *result) {
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
if (result == NULL) {
fprintf(stderr, "Result set is NULL.\n");
return;
}
//获取字段数
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result))) {
for (i = 0; i < num_fields; i++) {
printf("%s\t", row[i] ? row[i] : "NULL");
}
printf("\n");
}
}