garten
view db.c @ 20:17b2bcc42d72
added check for empty result; minor stuff
author | meillo@marmaro.de |
---|---|
date | Sun, 27 Jul 2008 21:34:54 +0200 |
parents | 5937504619f2 |
children |
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "db.h"
7 void db_error(char* info) {
8 fprintf(stderr, "%s%sSQL error: %s\n", (info) ? info : "", (info) ? ": " : "", sqlite3_errmsg(db));
9 }
12 void db_connect() {
13 if (sqlite3_open(database, &db) != SQLITE_OK) {
14 fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
15 sqlite3_close(db);
16 exit(1);
17 }
18 }
21 void db_close() {
22 sqlite3_close(db);
23 }
26 sqlite3_stmt* db_query(char* query) {
27 int error;
28 sqlite3_stmt* stmt;
30 error = sqlite3_prepare(db, query, -1, &stmt, NULL);
31 if (error) {
32 fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
33 }
34 return stmt;
35 }
39 int db_update(char* query) {
40 int error;
41 sqlite3_stmt* stmt;
43 error = sqlite3_prepare(db, query, -1, &stmt, NULL);
44 if (error || sqlite3_step(stmt) != SQLITE_DONE) {
45 fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
46 return 0;
47 }
48 return 1;
49 }
52 int db_rows(sqlite3_stmt* stmt) {
53 int i = 0;
55 sqlite3_reset(stmt);
56 while (sqlite3_step(stmt) == SQLITE_ROW) {
57 i++;
58 }
59 sqlite3_reset(stmt);
60 return i;
61 }
64 int read_time() {
65 int error;
67 sprintf(query, "select time from game;");
68 stmt = db_query(query);
69 error = sqlite3_step(stmt);
70 if (error == SQLITE_DONE) {
71 fprintf(stderr, "no game available\n");
72 exit(1);
73 }
74 if (error != SQLITE_ROW) {
75 db_error("read_time");
76 exit(1);
77 }
78 gametime = sqlite3_column_int(stmt, 0);
79 sqlite3_finalize(stmt);
80 return gametime;
81 }