Database Access

0.2

Database interface

The database interface is based on the ROOT abstract SQL database interface TSQLServer The code in this library (see Database classes) is a reimplementation of that interface, and does not require ROOT.

Currently supported backends are

  • MySQL - requires the MySQL C client API.
  • Oracle - requires the Oracle C++ client API.

An instance of a database connection is made using the static member funtion RcuDb::Server::Connect, passing a URL as argument. The URL is a standard conforming URL

    http://user:pass@example.com:992/animal/bird?species=seagull#wings
    \___/  \________/\_________/\__/\__________/\______________/\____/
      |        |          |       |       |             |          |
    scheme   login      hosts   port    path          query  anchor/fragment
    

The schema selects the database management type (e.g., mysql or oracle). The user part selects the database user name to use, pass is the (optional) password for user. The host part selects the server host, and the port number is specified in port. The path part selects the database, and the query part specifies options for the connection (database managment system dependent). The anchor part is generally ignored.

To make a connection, do for example

    RcuDb::Url url("mysql://config@localhost/Rcu");
    RcuDb::Server* server = RcuDb::Server::Connect(url);
    if (!server) {
      std::cerr << "Failed to connect to server " << url << std::endl;
      return 1;
    }

Next, we can do queries on the data base tables

    RcuDb::Sql query;
    query << "SELECT * FROM Config WHERE id=" << id;
    RcuDb::Result* result = server->Query(query);
    if (!result) {
      std::cerr << "Query failed: " << server->ErrorString() 
                << std::Endl;
      return 1;
    }

The class RcuConf::Sql is a used for making queries. It can be used as a std::ostream, meaning we can use the put-to operator to make the queries.

We should always chech the result we get back. If it is valid (not null), it does not nessecarily that we got rows back. We should use the RcuDb::Result::Next member function to get the results.

    RcuDb::Row* row = 0;
    while ((row = result->Next())) {

When we have a row we can extract data from it. The member function template RcuDb::Row::Field can return values of any type for which a standard get-from operator is defined

      int id;
      row->Field(0, id);
      std::string desc;
      row->Field(1, desc);
      // Process the row data 
    }

Once we're done with the result, we should delete it

    delete result;
Top of page Last update Wed Jul 11 16:56:53 2007
Copyright © 2004 Christian Holm Created by DoxyGen 1.5.2