[odb-users] How to run a select query to a DB from C++?

Boris Kolpackov boris at codesynthesis.com
Mon Sep 4 05:30:48 EDT 2023


Visa Karthick <Visa.Karthick at irisi.com.au> writes:

>         odb::transaction t2(db->begin());
>         // Find function should be invoked here
>         auto tankType = std::make_shared<EntityType>("Tank");
>         db->persist(tankType.get()); // This inserts a new record with value Tank in the   EntityType table.
>         t2.commit();
> 
> The above code works fine for inserting records in to a Sqlite table.
> The problem is it keeps adding the same row again and again When I run
> the program. I need to insert records only when the table is empty. There
> is another function for running a select query in the database. It is
> invoked by the below code.
> 
>      template <typename T>
>      inline typename object_traits<T>::pointer_type database::
>      find (const typename object_traits<T>::id_type& id)
>      {
>      return find_<T, id_common> (id);
>      }
> 
> I need to invoke the find function first, and only if it doesnt return
> any result persist function should be called. I am unsure what parameters
> to be passed from my current scope. Could you please advise?

The usage of the database::find() function is discussed in Section 3.9,
"Loading Persistent Objects":

https://www.codesynthesis.com/products/odb/doc/manual.xhtml#3.9

Specifically, the argument to find() is the object id (i.e., the
value that corresponds to data member marked with `#pragma db id`).
Since you didn't provide the definition for the EntityType class,
it's unclear whether "Tank" is the object id. If it is, then that's
what you would pass to find(). If it's not, then you will need to
run a query to determine if an object a with non-id data member
"Tank" is already in the database. For that see Section 2.5, "Querying
the Database for Objects":

https://www.codesynthesis.com/products/odb/doc/manual.xhtml#2.5



More information about the odb-users mailing list