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