C++, Linux

Select from SqLite with C++ in Linux

If you are using Ubuntu Linux, you can install sqlite headers by issuing the following command:

sudo apt-get install libsqlite3-dev

The code:

#include <iostream>
#include <sqlite3.h>
using namespace std;
 
static int print_results(void *notInUse, int argc, char **argv, char **colName)
{
	int i;
	for(i=0; i<argc; i++)
		cout << colName[i] << " = " << (argv[i] ? argv[i] : "-") << endl;
	cout << endl;
	return 0;
}
 
 
int main() {
	sqlite3 *db;
	char *errMsg = 0;
 
	//open database connection
	int conn = sqlite3_open("/home/username/test/databases/testdb1", &db);
 
	if(conn)
		cout << "Error: Can't open databasen";
 
	//execute select query
	const char *query = "select * from persons;";
	conn = sqlite3_exec(db, query, print_results, 0, &errMsg);
    	if(conn != SQLITE_OK)
    	{
      		cout << "Error: " << errMsg << endl;
      		sqlite3_free(errMsg);
    	}  
 
	//close database connection
	if(db)
	    sqlite3_close(db);
 
	return 0;
}