summaryrefslogtreecommitdiff
path: root/lib/SQL.cc
blob: 6ce606ce54f30b626fdb0776576a42a0663aa4af (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_MYSQL
#ifdef _WIN32
#include <winsock.h>
#endif

#include "SQL.h"

SQLConnection::SQLConnection(const String & host, const String & user, const String & passwd,
                             const String & db, int port, const String & socket,
			     unsigned long cflags) throw (GeneralException) : res(0) {
    mysql_init(&con);
    
    const char * phost = ((ugly_string) host).p;
    const char * puser = ((ugly_string) user).p;
    const char * ppasswd = ((ugly_string) passwd).p;
    const char * pdb = ((ugly_string) db).p;
    const char * psocket = ((ugly_string) socket).p;
    
    phost = *phost ? phost : 0;
    psocket = *psocket ? psocket : 0;
    
    if (!mysql_real_connect(&con, phost, puser, ppasswd, pdb, port, psocket, cflags)) {
	throw GeneralException("Could not connect to MySQL host " + host);
    }
}

SQLConnection::~SQLConnection() {
    mysql_close(&con);
}

int SQLConnection::query(const String & q) {
    int r;

    if (res) {
	mysql_free_result(res);
    }

    res = 0;

    if ((r = mysql_real_query(&con, ((ugly_string)q).p, q.strlen()))) {
        return r;
    }
    
    res = mysql_store_result(&con);
    
    if (res) {
	nr = mysql_num_rows(res);
	nf = mysql_num_fields(res);
	fields = mysql_fetch_fields(res);
        na = mysql_affected_rows(&con);
        ii = mysql_insert_id(&con);
    } else {
	nr = 0;
	nf = 0;
	fields = 0;
        na = 0;
        ii = -1;
    }

    return r;
}

int SQLConnection::numrows() {
    return nr;
}

int SQLConnection::numfields() {
    return nf;
}

AssocArray SQLConnection::fetchrow() {
    AssocArray r;
    MYSQL_ROW row;
    int i;
    
    row = mysql_fetch_row(res);
    
    for (i = 0; i < nf; i++) {
	r[fields[i].name] = row[i];
    }
    
    return r;
}

int SQLConnection::numaffectedrows() {
    return na;
}

int SQLConnection::insertid() {
    return ii;
}

//int SQLConnection::errno() {
//    return mysql_errno(&con);
//}

String SQLConnection::error() {
    return mysql_error(&con);
}

#endif