Created
June 15, 2012 14:34
-
-
Save jsok/2936764 to your computer and use it in GitHub Desktop.
sqlite3 C example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Can you please tell me how to use sqliteasync.c for asynchronous process.?
Thank you. This is the simple, complete example that SQLite should have on their Website.
Thanks
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.
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
This was very helpful, thank you for sharing