simple sqlite integration for save games

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
Sundar
Posts: 84
Joined: Mon Jun 05, 2006 11:05 am

simple sqlite integration for save games

Post by Sundar »

I have implemented a simple sqlite based save game system. I thought it might be useful for the community. I have tested this code with irrlicht 1.6 and works fine.
The Header File

Code: Select all

#ifndef SQLMANAGER_H
#define SQLMANAGER_H
#define SQLITE_CORE
#include <irrlicht.h>
#include <irrarray.h>
extern "C" {

#include "../sqlite/sqlite3.h"
#include "../sqlite/sqlite3ext.h"
}
static irr::core::array<irr::core::stringc> result;
class SQLManager
{
private:
	sqlite3 *db;
	char *zErrMsg;
	int rc;
//	
public:
       void init(irr::core::stringc fname);
	void release();
	irr::core::array<irr::core::stringc>  Query(irr::core::stringc fname ,irr::core::stringc query);

};
#endif
The cpp file

Code: Select all

#include "SQLManager.h"
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
	irr::core::stringc msg;
	for(int i = 0; i < argc; i++)
	{
		msg += argv[i];
		msg += " "; // space is the delimiter i use, feel free to change this.
		
	}
	result.push_front(msg);
	return 0;
}


void SQLManager::init(irr::core::stringc fname)
{
	rc = sqlite3_open(fname.c_str(), &db);
	if( rc ){
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);

	}
}
void SQLManager::release()
{
sqlite3_close(db);
}
irr::core::array<irr::core::stringc>  SQLManager::Query(irr::core::stringc fname , irr::core::stringc query)
{
	init(fname);
	result.clear();
	rc = sqlite3_exec(db, query.c_str(), callback, 0, &zErrMsg);
	if( rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}
	release();
	return result;

}

usage snippet

Code: Select all

// note result is the global variable i am using to retrieve the query results
	result = pManager->SQLdb.Query("select name from profile");
// be cautious using this in update loop. make sure you call it once not each & every time else performance will suffer
ACE247
Posts: 704
Joined: Tue Mar 16, 2010 12:31 am

Post by ACE247 »

Nice how-come no-one saw this? :)
Josie
Posts: 44
Joined: Sat Jul 25, 2009 4:08 am
Location: Griffin, Georgia, US
Contact:

Post by Josie »

Good work, but I'd like to see it used as a generic container that you can save() and load().

So you could do...

Code: Select all

persistent->write("name", username);
persistent->save();
And load it back later with ( maybe add a dynamic cast )

Code: Select all

string username = persistent->load("name");
Post Reply