-
Notifications
You must be signed in to change notification settings - Fork 3
/
mysql_api.c
81 lines (67 loc) · 1.36 KB
/
mysql_api.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "mysql_api.h"
#include "bit_func.h"
#ifndef MYSQL_USER
#define MYSQL_USER "root"
#endif
#ifndef MYSQL_PASS
#define MYSQL_PASS ""
#endif
#ifndef MYSQL_DBNAME
#define MYSQL_DBNAME "celldb"
#endif
#ifdef USE_MYSQL
#include <mysql.h>
static MYSQL *meta_db;
#endif
void mysql_api_query_cb(const char *input)
{
const char *ptr = input;
char query[4096];
int ret;
assert(input != NULL);
if (input[0] == 0) {
return;
}
#ifdef USE_MYSQL
while (sgets(query, sizeof(query), &ptr)) {
ret = mysql_query(meta_db, query);
if (ret) {
printf("Error executing query:\n%s\n", query);
printf("MySQL error: %s\n", mysql_error(meta_db));
exit(1);
}
}
#endif
}
void mysql_api_init(struct session_info *s)
{
#ifdef USE_MYSQL
int ret, one = 1;
MYSQL *conn_check;
/* Connect to database */
meta_db = mysql_init(NULL);
ret = mysql_options(meta_db, MYSQL_OPT_RECONNECT, &one);
if (ret) {
printf("Cannot set database options\n");
exit(1);
}
conn_check = mysql_real_connect(meta_db, "localhost", MYSQL_USER, MYSQL_PASS, MYSQL_DBNAME, 3306, 0, 0);
if (!conn_check) {
printf("Cannot open database\n");
exit(1);
}
s->sql_callback = mysql_api_query_cb;
#else
s->sql_callback = NULL;
#endif
}
void mysql_api_destroy()
{
#ifdef USE_MYSQL
mysql_close(meta_db);
#endif
}