-
-
Save anytizer/44bdc76947b302f22c5c1b67a83d2627 to your computer and use it in GitHub Desktop.
c++ sqlite3 create table and insert example
This file contains hidden or 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
// From: https://gist.github.com/lotfio/cfbf857bc96a0487b53ed4877658a97b | |
// Fork: https://gist.github.com/anytizer/44bdc76947b302f22c5c1b67a83d2627 | |
/** | |
* Minor Improvements: | |
* Sqlite => DatabaseManager. | |
* One lined insert statements. | |
* Embedded SQLite3 source code from amalgamation. | |
* Access pointer with "this". | |
* OS/compiler specific full path to the database name. | |
* Text conversion in the database fields. | |
* Tick quoted database fields. | |
*/ | |
#ifdef _WIN64 | |
#define DATABASE_PATH "/tmp/database.db" | |
#elif !_WIN64 | |
#define DATABASE_PATH "/tmp/database.db" | |
#endif | |
//#include <iostream> | |
#include "sqlite3.h" | |
static int callback(void *NotUsed, int argc, char **argv, char **azColName) | |
{ | |
return 0; | |
} | |
class DatabaseManager | |
{ | |
public: | |
sqlite3* db; | |
public: | |
DatabaseManager(const char* fullpath) | |
{ | |
sqlite3_open(fullpath, &this->db); | |
} | |
~DatabaseManager() | |
{ | |
sqlite3_close(this->db); | |
} | |
int execute(const char* sql,int (*callback)(void *, int, char **, char **), char* err = 0) | |
{ | |
return sqlite3_exec(this->db, sql, callback, 0, &err); | |
} | |
}; | |
int main(void) | |
{ | |
DatabaseManager conn = DatabaseManager(DATABASE_PATH); | |
const char* q1 = \ | |
"CREATE TABLE `employees` (" \ | |
"`id` TEXT NOT NULL," \ | |
"`name` TEXT NOT NULL," \ | |
"`age` TEXT NOT NULL," \ | |
"`address` TEXT NOT NULL," \ | |
"`salary` TEXT NOT NULL," \ | |
"PRIMARY KEY(`id`)" \ | |
");" \ | |
; | |
conn.execute(q1, callback); | |
const char* q2 = \ | |
"INSERT INTO `employees` (`id`, `name`, `age`, `address`, `salary`) VALUES ('001', 'Paul', '32', 'Calif', '20000.00');" \ | |
"INSERT INTO `employees` (`id`, `name`, `age`, `address`, `salary`) VALUES ('002', 'Allen', '25', 'Texas', '15000.00');" \ | |
"INSERT INTO `employees` (`id`, `name`, `age`, `address`, `salary`) VALUES ('003', 'Teddy', '23', 'Norwy', '20000.00');" \ | |
"INSERT INTO `employees` (`id`, `name`, `age`, `address`, `salary`) VALUES ('004', 'Mark', '25', 'RichM', '65000.00');" \ | |
"INSERT INTO `employees` (`id`, `name`, `age`, `address`, `salary`) VALUES ('005', 'Test', '30', 'Addre', '60000.00');" \ | |
"INSERT INTO `employees` (`id`, `name`, `age`, `address`, `salary`) VALUES ('006', 'Sixt', '60', 'Addre', '60000.00');" \ | |
; | |
conn.execute(q2, callback); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment