By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,220 Members | 1,723 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,220 IT Pros & Developers. It's quick & easy.

class objects to database translation

P: n/a
Hi,

The problem is :

You have a class A with one or more data variables. You want to store the
data variables in a database for example MySQL. Also you do not want to have
SQL code in your class A. Is there a way to translate the Object A to a sql
independed structure. I think it is something with persistent objects or am
I wrong. has anyone experience with this ?

John
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Johan" <me@knoware.nl> wrote in message news:<10*************@corp.supernews.com>...
Hi,

The problem is :

You have a class A with one or more data variables. You want to store the
data variables in a database for example MySQL. Also you do not want to have
SQL code in your class A. Is there a way to translate the Object A to a sql
independed structure. I think it is something with persistent objects or am
I wrong. has anyone experience with this ?

John


What I've done in this situation is implement a container-like class
hierarchy that encapsulates all of the database functionality. For
each class that you want to store in the database you create a new
container class that knows how to translate the database
representation into the C++ representation.

Here's the (very) basic idea:

class Foo { /* a normal class */ };

class Database { /* execute SQL statements using MySQL API */ };

template <typename Type>
class DatabaseSet
{
public :
// implement a persistent container interface
class Iterator;
class ConstIterator;
DatabaseSet& store(); // store objects in database using SQL
DatabaseSet& retrieve(); // retrieve objects from database using
SQL
Iterator insert(const Type& type);
ConstIterator find(const Type& target) const;
Iterator find(const Type& target);
// etc.
virtual ~DatabaseSet();

protected :
DatabaseSet(const Database& database) {} // abstract base class
// generate SQL statements
virtual std::string select_query() const = 0;
virtual std::string insert_query(const Type& type) const = 0;
virtual std::string update_query(const Type& type) const = 0;

private :
SomeContainer<Type> m_container;
Database m_database; // connection to MySQL database
};

class FooSet : public DatabaseSet<Foo>
{
public :
FooSet(const Database& database) : DatabaseSet<Foo>(database) {}

private :
// Foo-specific SQL
virtual std::string select_query() const;
virtual std::string insert_query() const;
virtual std::string update_query() const;
};
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.