#include #include #include "sqlite3.h" using namespace std; int foundRecord(void *p, int argc, char **argv, char **colName) { for (int i = 0; i < argc; ++i) { if (i > 0) { cout << "\t"; } cout << argv[i]; } cout << "\n"; return SQLITE_OK; } int main(int argc, char **argv) { sqlite3 *base = 0; if (sqlite3_open("database.db", &base) != SQLITE_OK) { cerr << argv[0] << ": sqlite3_open: " << sqlite3_errmsg(base) << "\n"; return 1; } //An sql statement ends with a semicolon. char *error = 0; if (sqlite3_exec(base, "drop table if exists people;", 0, 0, &error) != SQLITE_OK) { cerr << argv[0] << ": sqlite3_exec: " << error << "\n"; sqlite3_free(error); sqlite3_close(base); return 2; } const char *const create = "create table people (\n" " lastname text,\n" " firstname text,\n" " ss integer primary key\n" ");"; if (sqlite3_exec(base, create, 0, 0, &error) != SQLITE_OK) { cerr << argv[0] << ":sqlite3_exec: " << error << "\n"; sqlite3_free(error); sqlite3_close(base); return 3; } typedef struct { const char *lastname; const char *firstname; int ss; } person_t; const person_t a[] = { {"Catalano", "Michael", 1}, {"Dafferner", "Michael", 2}, {"Fisher", "Tristan", 3}, {"Gallucci", "Gregory", 4}, {"Hunter", "Andrew", 5}, {"Marsala", "John", 6}, {"Mehta", "Saumil", 7}, {"Meretzky", "Mark", 8}, {"Onwuachi", "Udoma", 9}, {"O'rtiz", "Florencia", 10}, {"Pennisten", "John", 11}, {"Popa", "Cristian", 12}, {"Raghfar", "Mahdi", 13}, {"Roberd-Clark", "Gates", 14}, {"Singh", "Rana", 15} }; static const size_t n = sizeof a / sizeof a[0]; for (size_t i = 0; i < n; ++i) { char *const insert = sqlite3_mprintf( "insert into people (lastname, firstname, ss) values ('%q', '%q', %d);", a[i].lastname, a[i].firstname, a[i].ss ); if (insert == 0) { cerr << argv[0] << ": sqlite3_mprintf failed.\n"; continue; } cout << insert << "\n"; char *error = 0; if (sqlite3_exec(base, insert, 0, 0, &error) != SQLITE_OK) { cerr << argv[0] << ": " << error << "\n"; sqlite3_free(error); continue; } sqlite3_free(insert); } /* The following sqlite3_exec will call foundRecord over and over again, once for each record that it finds. The first argument that sqlite3_exec passes to foundRecord will be the html string. */ if (sqlite3_exec(base, "select firstname, lastname from people where length(firstname) == length(lastname)", foundRecord, 0, &error) != SQLITE_OK) { cerr << argv[0] << ": " << error << "\n"; sqlite3_free(error); sqlite3_close(base); return 4; } sqlite3_exec(base, "delete from people where lastname like 'M%';", 0, 0, &error); if (sqlite3_close(base) != SQLITE_OK) { cerr << argv[0] << ": sqlite3_close failed.\n"; return 5; } return EXIT_SUCCESS; }