annotate db.c @ 18:5937504619f2
rename game.h -> modules.h; added some error handling; and more
author |
meillo@marmaro.de |
date |
Wed, 23 Jul 2008 17:40:55 +0200 |
parents |
5e6c9260913a |
children |
17b2bcc42d72 |
rev |
line source |
meillo@15
|
1 #include <stdio.h>
|
meillo@15
|
2 #include <stdlib.h>
|
meillo@15
|
3 #include "db.h"
|
meillo@15
|
4
|
meillo@15
|
5
|
meillo@15
|
6
|
meillo@15
|
7 void db_connect() {
|
meillo@15
|
8 if (sqlite3_open(database, &db) != SQLITE_OK) {
|
meillo@15
|
9 fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
|
meillo@15
|
10 sqlite3_close(db);
|
meillo@15
|
11 exit(1);
|
meillo@15
|
12 }
|
meillo@15
|
13 }
|
meillo@15
|
14
|
meillo@15
|
15
|
meillo@15
|
16 void db_close() {
|
meillo@15
|
17 sqlite3_close(db);
|
meillo@15
|
18 }
|
meillo@15
|
19
|
meillo@15
|
20
|
meillo@15
|
21 sqlite3_stmt* db_query(char* query) {
|
meillo@15
|
22 int error;
|
meillo@15
|
23 sqlite3_stmt* stmt;
|
meillo@15
|
24
|
meillo@15
|
25 error = sqlite3_prepare(db, query, -1, &stmt, NULL);
|
meillo@15
|
26 if (error) {
|
meillo@15
|
27 fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
|
meillo@15
|
28 }
|
meillo@15
|
29 return stmt;
|
meillo@15
|
30 }
|
meillo@15
|
31
|
meillo@15
|
32
|
meillo@15
|
33
|
meillo@15
|
34 int db_update(char* query) {
|
meillo@15
|
35 int error;
|
meillo@15
|
36 sqlite3_stmt* stmt;
|
meillo@15
|
37
|
meillo@15
|
38 error = sqlite3_prepare(db, query, -1, &stmt, NULL);
|
meillo@15
|
39 if (error || sqlite3_step(stmt) != SQLITE_DONE) {
|
meillo@15
|
40 fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
|
meillo@15
|
41 return 0;
|
meillo@15
|
42 }
|
meillo@15
|
43 return 1;
|
meillo@15
|
44 }
|
meillo@15
|
45
|
meillo@15
|
46
|
meillo@17
|
47 int db_rows(sqlite3_stmt* stmt) {
|
meillo@17
|
48 int i = 0;
|
meillo@17
|
49
|
meillo@17
|
50 sqlite3_reset(stmt);
|
meillo@17
|
51 while (sqlite3_step(stmt) == SQLITE_ROW) {
|
meillo@17
|
52 i++;
|
meillo@17
|
53 }
|
meillo@17
|
54 sqlite3_reset(stmt);
|
meillo@17
|
55 return i;
|
meillo@17
|
56 }
|
meillo@17
|
57
|
meillo@17
|
58
|
meillo@15
|
59 int read_time() {
|
meillo@15
|
60 sprintf(query, "select time from game;");
|
meillo@16
|
61 stmt = db_query(query);
|
meillo@15
|
62 if (sqlite3_step(stmt) != SQLITE_ROW) {
|
meillo@15
|
63 printf("error: %s\n", sqlite3_errmsg(db));
|
meillo@15
|
64 exit(1);
|
meillo@15
|
65 }
|
meillo@15
|
66 gametime = sqlite3_column_int(stmt, 0);
|
meillo@15
|
67 sqlite3_finalize(stmt);
|
meillo@15
|
68 return gametime;
|
meillo@15
|
69 }
|
meillo@15
|
70
|
meillo@17
|
71
|
meillo@17
|
72 void db_error(char* info) {
|
meillo@17
|
73 fprintf(stderr, "%s%sSQL error: %s\n", (info) ? info : "", (info) ? ": " : "", sqlite3_errmsg(db));
|
meillo@17
|
74 }
|