[gameprogrammer] sqlite example program

  • From: Chris Nystrom <cnystrom@xxxxxxxxx>
  • To: gameprogrammer@xxxxxxxxxxxxx
  • Date: Sat, 22 May 2010 00:56:59 -0500

Below is an example c program that I wrote to use the SQLite library
(http://www.sqlite.org/). It compiles without error under Linux.

SQLite seems to be far more trouble to use than simply creating
arrays. I assume that as you scale up though, it is important for
performance to have an actual database instead of internal arrays of
data. Is there a rule of thumb about when you should use a database?
Or is there some other reason to use SQL besides performance with
large systems?

Chris

--

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

sqlite3 *db;

void open_db(char *db_name)
{
    if (sqlite3_open(db_name, &db)) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
    }
}

char **result;
int nrow = 0;
int ncol = 0;

int db_exe(char *s_exe)
{
    int rc;
    char *zErrMsg = 0;

    rc = sqlite3_get_table(db,  /* An open database */
                           s_exe,       /* SQL to be executed */
                           &result,     /* Result written to a char *[] */
                           &nrow,       /* Number of result rows */
                           &ncol,       /* Number of result columns */
                           &zErrMsg     /* Error msg written here */
        );

    return rc;
}

void db_close(void)
{
    sqlite3_close(db);
}

void get_data(void)
{
    int i, j;

    if (nrow > 0) {

        printf("nrow = %d\n", nrow);
        printf("ncol = %d\n\n", ncol);

        /* header */
        for (i = 0; i < ncol; ++i)
            printf("%s\t", result[i]);
        printf("\n");

        /* data rows */
        for (i = 0; i < nrow; i++) {
            for (j = 0; j < ncol; j++) {
                printf("%s\t", result[(ncol * (i + 1)) + j]);
            }
            printf("\n");
        }
    }

    sqlite3_free_table(result);
}

int main(int argc, char **argv)
{
    char *db_name = "test.db";

    /* remove old db if it exists */
    remove(db_name);

    /* create db */
    open_db(db_name);

    /* create emp table */
    db_exe("create table emp (name varchar(15),age int,weight double)");

    /* insert data into tables */
    db_exe("insert into emp (name,age,weight) values ('Bob',47,172)");
    db_exe("insert into emp (name,age,weight) values ('Sue',38,134)");

    /* show data in emp table */
    db_exe("select * from emp");

    get_data();

    return 0;
}

-- 
E-Mail: Chris Nystrom <cnystrom@xxxxxxxxx>
Saving the world from web programming.
http://www.newio.org - G-Talk: cnystrom

---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: