void create_entry(struct Person *data)
{
int i;
sqlite3 *db;
char *zErrMsg = 0;
if (sqlite3_open("abook.db", &db) == SQLITE_OK) {
/* Create table if it doesn't exist */
char *sql = "CREATE TABLE IF NOT EXISTS PEOPLE (" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS TEXT NOT NULL," \
"ZIP INT NOT NULL," \
"CITY TEXT NOT NULL," \
"COUNTRY TEXT NOT NULL," \
"PHONE TEXT NOT NULL );";
if (sqlite3_exec(db, sql, callback, 0, &zErrMsg) != SQLITE_OK) {
fprintf(stderr, "SQL error: %s", zErrMsg);
sqlite3_free(zErrMsg);
}
/* How many rows does the table have? */
int rows = 0;
sqlite3_stmt *stmt;
sql = "SELECT COUNT(*) FROM PEOPLE";
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
if (sqlite3_step(stmt) == SQLITE_ERROR) {
fprintf(stderr, "Error counting rows %s", sqlite3_errmsg(db));
exit(0);
} else {
rows = sqlite3_column_int(stmt, 0);
}
}
sqlite3_finalize(stmt);
/* Add entry to table */
sql = "INSERT INTO PEOPLE (ID,NAME,AGE,ADDRESS,ZIP,CITY,COUNTRY,PHONE) " \
"VALUES (";
char *srows;
sprintf(srows, "%d", rows);
strcat(sql, srows); strcat(sql, ", ");
strcat(sql, data->name); strcat(sql, ", ");
strcat(sql, data->age); strcat(sql, ", ");
strcat(sql, data->address); strcat(sql, ", ");
strcat(sql, data->zip); strcat(sql, ", ");
strcat(sql, data->city); strcat(sql, ", ");
strcat(sql, data->country); strcat(sql, ", ");
strcat(sql, data->phone); strcat(sql, " );");
if (sqlite3_exec(db, sql, callback, 0, &zErrMsg) == SQLITE_OK) {
fprintf(stdout, "Successfully added entry to database\n");
} else {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
} else {
fprintf(stderr, "Error opening database: %s\n", sqlite3_errmsg(db));
exit(0);
}
sqlite3_close(db);
}