DVX_GUI/sql/thirdparty/sqlite/examples/example2.cpp

71 lines
1.6 KiB
C++

#include <stdio.h>
#include "sqlite3.h"
// This is the callback function to display the select data in the table
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
int i;
for(i=0; i<argc; i++)
{
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[])
{
sqlite3 *db; // sqlite3 db struct
char *zErrMsg = 0;
int rc;
// Open the test.db file
rc = sqlite3_open("ex2.db", &db);
if( rc ){
// failed
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
}
else
{
// success
fprintf(stderr, "Opened database successfully\n\n");
}
const char *pSQL[6];
// Create a new myTable in database
pSQL[0] = "create table myTable (FirstName varchar(30), LastName varchar(30), Age smallint)";
// Insert first data item into myTable
pSQL[1] = "insert into myTable (FirstName, LastName, Age) values ('Washington', 'George', 22)";
// Insert second data item into myTable
pSQL[2] = "insert into myTable (FirstName, LastName, Age) values ('Lincoln', 'Abraham', 33)";
// Select all data in myTable
pSQL[3] = "select * from myTable";
// Remove all data in myTable
pSQL[4] = "delete from myTable";
// Drop the table from database
pSQL[5] = "drop table myTable";
// execute all the sql statement
for(int i = 0; i < 6; i++)
{
rc = sqlite3_exec(db, pSQL[i], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
break;
}
}
sqlite3_close(db);
return 0;
}