AsiaBSDCon 2017 Secure CGI

Database example

Database example

    1 /* Title: Database example */
    2 
    3 #include <inttypes.h>
    4 #include <stdlib.h>
    5 #include <stdio.h>
    6 
    7 #include <ksql.h>
    8 
    9 int
   10 main(void)
   11 {
   12 	struct ksql	*sql;
   13 	struct ksqlstmt	*stmt;
   14 	int64_t		 hits;
   15 
   16 	/* First, initialise, open, read, then close the db. */
   17 
   18 	sql = ksql_alloc(NULL);
   19 	ksql_open(sql, "simple.db");
   20 	ksql_stmt_alloc(sql, &stmt, 
   21 		"UPDATE hits SET hits=hits+1", 0);
   22 	ksql_stmt_step(stmt);
   23 	ksql_stmt_free(stmt);
   24 	ksql_stmt_alloc(sql, &stmt, 
   25 		"SELECT hits FROM hits", 0);
   26 	ksql_stmt_step(stmt);
   27 	hits = ksql_stmt_int(stmt, 0);
   28 	ksql_stmt_free(stmt);
   29 	ksql_free(sql);
   30 
   31 	/* Now print the result. */
   32 
   33 	puts("Status: 200 OK\r");
   34 	puts("Content-Type: text/html\r");
   35 	puts("\r");
   36 	printf("Hello, world: %" PRId64 "\n", hits);
   37 
   38 	return(EXIT_SUCCESS);
   39 }
gcc -I/usr/local/include -static -o database database.c -L/usr/local/lib -lksql -lsqlite3