Table of Contents

G#+TITLE: sqlite3 examples

Basically this document needs to be tangled C-c C-v t And then evaluated. M-x org-babel-execute-buffer It will create or use a sqlite3 db file test.db And add a table named Foo with a few columns.

1. Create empty db

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

#include <sqlite3.h>

int
main(void)
{
  sqlite3 *db;
  char *zErrMsg = 0;
  int rc;

  rc = sqlite3_open("test.db", &db);
  if (rc) {
    fprintf(stderr, "Can't open database %s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    return EXIT_FAILURE;
  }
  sqlite3_close(db);
  puts("");

  return EXIT_SUCCESS;
}

1.1. Compile that

cc -o foo -static -I/usr/local/include foo.C -L/usr/local/lib -lsqlite3 -lpthread -lm

1.2. Run that

./foo

2. Create table of first-name last-name

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

#include <sqlite3.h>

static int callback(void *, int, char **, char **);

int
main(void)
{
  sqlite3 *db;
  char *zErrMsg = 0;
  int rc;

  rc = sqlite3_open("test.db", &db);
  if (rc) {
    fprintf(stderr, "Can't open database %s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    return EXIT_FAILURE;
  }
  rc = sqlite3_exec(db, "CREATE TABLE Foo ("
		    "Key int, "
		    "Name varchar(255), "
		    "Story text)",
		    callback, 0, &zErrMsg);
  if (rc) {
    fprintf(stderr, "SQL failure %s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    return EXIT_FAILURE;
  }


  sqlite3_close(db);
  puts("");

  return EXIT_SUCCESS;
}

static int callback(void *NotUsed, int N, char **results, char **azColName) {
  int i;
  ;
  return EXIT_SUCCESS;
}

2.1. Compile that

cc -o bar -static -I/usr/local/include bar.C -L/usr/local/lib -lsqlite3 -lpthread -lm

2.2. Run that

; It will fail to create the table a second time if you run it more than once. (Which doesn't matter a lot here)

./bar

2.3. Check result using SQL explorer utility

sqlite3 test.db <<EOG
.dump Foo	
.quit
EOG		
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE Foo (Key int, Name varchar(255), Story text);
COMMIT;

3. Do nothing as a C program

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

int
main(void) {

printf("Status: 200 OK\r\n");
printf("Content-Type: text/html\r\n");
printf("\r\n");

printf("This was an informational org file");

return EXIT_SUCCESS;
}

Author: Jake

Created: 2022-11-14 Mon 04:07