Skip to content

Instantly share code, notes, and snippets.

@HSchmale16 HSchmale16/makefile Secret
Last active Aug 29, 2015

Embed
What would you like to do?
Sqlite3 Example of Prepared Statements
.PHONY: all
all: test.cpp
g++ test.cpp -lsqlite3
.PHONY: clean
clean:
rm a.out
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
#include <sqlite3.h>
sqlite3* db;
const char sql_tb[] =
"CREATE TABLE FOO("
"ID INTEGER PRIMARY KEY AUTOINCREMENT, "
"A INTEGER, "
"B TEXT, "
"C REAL);";
const char sql_insert[] =
"INSERT INTO FOO(A, B, C) VALUES(?1, ?2, ?3);";
static int cb_table_make(void* notused, int argc, char** argv,
char** azColNm){
return 0;
}
static int cb(void* notused, int argc, char** argv,
char** azColNm){
for(int i = 0; i < argc; i++){
printf("%s = %s\n", azColNm[i], argv[0]);
}
return 0;
}
int main(){
srand(time(0));
char* zErrMsg;
int rc = sqlite3_open("a.sqlite", &db);
if(rc){
// handle error
fprintf(stderr, "%s\n", sqlite3_errmsg(db));
}
// Creating A Table
rc = sqlite3_exec(db, sql_tb, cb_table_make, 0, &zErrMsg);
if(rc){
printf("%s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
// Demo of Prepared Statements
sqlite3_stmt* stmt;
rc = sqlite3_prepare_v2(db, sql_insert, -1, &stmt, NULL);
if(rc){
puts("Failed to prepare statement\n");
}
for(int i = 0; i < 100; i++){
std::string str;
for(int n = 0; n < 10; n++){
str += rand() % 96 + 32;
}
sqlite3_bind_int(stmt, 1, i * rand());
sqlite3_bind_text(stmt, 2, str.c_str(), -1,
SQLITE_STATIC);
sqlite3_bind_double(stmt, 3,
(double)rand() / (double)rand());
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
// Select from the table
rc = sqlite3_exec(db, "SELECT * FROM FOO;", cb, 0, &zErrMsg);
if(rc){
// error handling, print zErrMsg and free it
printf("%s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
// close the database
sqlite3_close(db);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.