#ifndef __DATABASE_H__
#define __DATABASE_H__
#include <string>
#include <vector>
#include <sqlite3.h>
using namespace std;
class Database
{
public:
Database(char* filename);
~Database();
bool open(char* filename);
vector<vector<string> > query(char* query);
void close();
private:
sqlite3 *database;
};
#endif
==========================================================================
#include "Database.h"
#include <iostream>
Database::Database(char* filename)
{
database = NULL;
open(filename);
}
Database::~Database()
{
}
bool Database::open(char* filename)
{
if(sqlite3_open(filename, &database) == SQLITE_OK)
return true;
return false;
}
vector<vector<string> > Database::query(char* query)
{
sqlite3_stmt *statement;
vector<vector<string> > results;
if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK)
{
int cols = sqlite3_column_count(statement);
int result = 0;
while(true)
{
result = sqlite3_step(statement);
if(result == SQLITE_ROW)
{
vector<string> values;
for(int col = 0; col < cols; col++)
{
values.push_back((char*)sqlite3_column_text(statement, col));
}
results.push_back(values);
}
else
{
break;
}
}
sqlite3_finalize(statement);
}
string error = sqlite3_errmsg(database);
if(error != "not an error") cout << query << " " << error << endl;
return results;
}
void Database::close()
{
sqlite3_close(database);
}
===========================================================================
#include <iostream>
#include "Database/Database.h"
using namespace std;
Database *db;
db = new Database("Database.sqlite");
db->query("CREATE TABLE a (a INTEGER, b INTEGER);");
db->query("INSERT INTO a VALUES(1, 2);");
db->query("INSERT INTO a VALUES(5, 4);");
vector<vector<string> > result = db->query("SELECT a, b FROM a;");
for(vector<vector<string> >::iterator it = result.begin(); it < result.end(); ++it)
{
vector<string> row = *it;
cout << "Values: (A=" << row.at(0) << ", B=" << row.at(1) << ")" << endl;
}
db->close();
===========================================================================
Above source extracted from :
http://www.dreamincode.net/forums/showtopic122300.htm
I was doing my project and i across the above code. But i am stuck, because after i extract data and wish to put it into database using the variable name, but unable to do so
May i know is it possible to insert into the database using variable name ?
eg.
int i = 100;
db->query("INSERT INTO a VALUES(5, i);");
the above statement prompt me no i columns found