server.h
#ifndef server_h
#define server_h
#include <stdio.h>
#include <stdlib.h>
#define false 0
#define true 1
typedef _Bool bool;
#endif
db.h
#ifndef db_h
#define db_h
#include <stdio.h>
#include <mysql.h>
#include <stdlib.h>
#include "server.h"
MYSQL *MI_con;
struct Db_row_link{
MYSQL_ROW data;
struct Db_row_link *next;
};
void db_connect(char*,char* ,char* ,char* );
bool db_query(const char*);
struct Db_row_link * query_result(const char*);
#endif
db.c
#ifndef db_c
#define db_c
/**
gcc db.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
*/
#include "db.h"
void db_connect(char* host,char* username,char* password,char* dbname){
if(MI_con==NULL){
MI_con = mysql_init(NULL);
if(!mysql_real_connect(MI_con,host,username,password,dbname,0,NULL,0)){
printf("Error connecting to mysql\n");
exit(0);
}else{
//printf("Connected mysql successful\n");
}
}
}
bool db_query(const char* sql){
if(MI_con!=NULL){
if(mysql_query(MI_con,sql)){
printf("%s\n",mysql_error(MI_con));
return false;
}
return true;
}
printf("%s\n",mysql_error(MI_con));
return false;
}
struct Db_row_link * query_result(const char* sql){
MYSQL_RES *res;
MYSQL_ROW row;
if(MI_con!=NULL){
if(!(res=mysql_store_result(MI_con))){
printf("%s\n",mysql_error(MI_con));
return NULL;
}
struct Db_row_link *p1,*p2;
struct Db_row_link *head;
p1 = p2 = (struct Db_row_link *)malloc(sizeof(struct Db_row_link));
int n =0;
while((row=mysql_fetch_row(res))!=NULL){
if(n==0){
head = p1;
p1 = (struct Db_row_link *)malloc(sizeof(struct Db_row_link));
head->next = p1;
n=1;
}else{
p1 = (struct Db_row_link *)malloc(sizeof(struct Db_row_link));
p2->next = p1;
}
p2 = p1;
p1->data = row;
p1->next = NULL;
//printf("%s\t%s\n",row[0],row[1]);
}
mysql_free_result(res);
return head;
}
return NULL;
}
int main(){
char* host = "localhost";
char* username = "root";
char* password = "root";
char* dbname = "test";
db_connect(host,username,password,dbname);
const char* sql = "SELECT * FROM my_test";
if(db_query(sql)){
struct Db_row_link *mdata = query_result(sql);
while((mdata = mdata->next)!=NULL){
printf("%s\t%s\n",mdata->data[0],mdata->data[1]);
}
}
return 0;
}
#endif
c mysql操作
最新推荐文章于 2023-09-22 07:01:03 发布