Skip to content

Instantly share code, notes, and snippets.

@jsok
Created June 15, 2012 14:34
Show Gist options
  • Save jsok/2936764 to your computer and use it in GitHub Desktop.
Save jsok/2936764 to your computer and use it in GitHub Desktop.
sqlite3 C example
#include <stdio.h>
#include <sqlite3.h>
int main(void)
{
sqlite3 *db;
sqlite3_stmt *stmt;
sqlite3_open("expenses.db", &db);
if (db == NULL)
{
printf("Failed to open DB\n");
return 1;
}
printf("Performing query...\n");
sqlite3_prepare_v2(db, "select * from expenses", -1, &stmt, NULL);
printf("Got results:\n");
while (sqlite3_step(stmt) != SQLITE_DONE) {
int i;
int num_cols = sqlite3_column_count(stmt);
for (i = 0; i < num_cols; i++)
{
switch (sqlite3_column_type(stmt, i))
{
case (SQLITE3_TEXT):
printf("%s, ", sqlite3_column_text(stmt, i));
break;
case (SQLITE_INTEGER):
printf("%d, ", sqlite3_column_int(stmt, i));
break;
case (SQLITE_FLOAT):
printf("%g, ", sqlite3_column_double(stmt, i));
break;
default:
break;
}
}
printf("\n");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
getc(stdin);
return 0;
}
Copy link

ghost commented Dec 7, 2020

WARNING:
This program will go into loop forever and print "\n" when the expenses.db file not exist with sqlite3 3.30.1
The call of sqlite3_step(stmt) return 21(SQLITE_MISUSE) in that status.

#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
 
//    Abort on failure of creating or opening a database;
//    True if created a new database file
//    False if it reuses
int sqlq_has_to_be_init(const char* path, sqlite3** db) {
  if(sqlite3_open_v2(path, db, SQLITE_OPEN_READWRITE, NULL)) {
     if (sqlite3_open_v2(path, db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL)) {
       fprintf(stderr,"%s:%d Can't open database: %s\n", __FILE__, __LINE__, sqlite3_errmsg(*db));
       sqlite3_close_v2(*db);
       exit(EXIT_FAILURE);
       //can't use the sqlite3* db object anymore, needs to be cleared in some way
       //can't bother for now
     } else {
       return 1;
     }
   } return 0;
}

int main(int argc, char** argv, char** envp) {
 sqlite3 *db;
 sqlite3_stmt *stmt;
 if(sqlq_has_to_be_init("expenses.db", &db)) {
   // do database initialisation shit;
 } else {
   // line 12-51
 }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment