C/C++ Programming Pearls

 
SQLite is an embeddable SQL Database Engine with an API for C and C++ programs. This is a very small, fast, database...sometimes much faster than MySQL; however, it really isn't a client server application

Download sqlite-2.x.x.tar.gz and install the program. After the program is installed, you may want to edit the following file:
/etc/ld.so.conf
Under Linux, SQLite will install the library files in /usr/local/lib, which should be added to /etc/ld.so.conf. In order for this change to take effect, run
$ldconfig


Creating a database and tables is easy from the bash shell. $sqlite test.db
This will create the file test.db in the current directory, and bring up the SQLite interface
SQLite version 2.8.0
Enter ".help" for instructions
sqlite>
Next, create table foo with an AUTOINCREMENT field and populate the table with some records.
sqlite>create table foo(
pkey INTEGER PRIMARY KEY,
fname varchar(15),
lname varchar(30),
age int);
sqlite> insert into foo (fname,lname,age) values ('mike','chirico',40);
sqlite> insert into foo (fname,lname,age) values ('zoe','chirico',2);
sqlite> insert into foo (fname,lname,age) values ('abby','chirico',2);
sqlite> insert into foo (fname,lname,age) values ('leah','chirico',2);
sqlite>.quit

apiSQLite.c is a sample interface program


apiSQLite.c
/*
gcc -o apiSQLite apiSQLite.c -lsqlite

./apiSQLite test.db "select * from foo"

*/
#include <stdio.h>
#include <sqlite.h>

    static int callback(void *NotUsed, int argc, char **argv, char **azColName){
      int i;
      for(i=0; i<argc; i++){
	printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
      }
      printf("\n");
      return 0;
}

int main(int argc, char **argv){
  sqlite *db;
  char *zErrMsg = 0;
  int rc;

  if( argc!=3 ){
    fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
    exit(1);
  }
  db = sqlite_open(argv[1], 0, &zErrMsg);
  if( db==0 ){
    fprintf(stderr, "Can't open database: %s\n", zErrMsg);
    exit(1);
  }
  rc = sqlite_exec(db, argv[2], callback, 0, &zErrMsg);
  if( rc!=SQLITE_OK ){
    fprintf(stderr, "SQL error: %s\n", zErrMsg);
  }
  sqlite_close(db);
  return 0;
}


*
SourceForge.net Logo