-
-
Save HSchmale16/bca38bf78786fdeb971c to your computer and use it in GitHub Desktop.
Sqlite3 Example of Prepared Statements
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
.PHONY: all | |
all: test.cpp | |
g++ test.cpp -lsqlite3 | |
.PHONY: clean | |
clean: | |
rm a.out |
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 <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