Product Documentation

c-treeDB API API for C

Previous Topic

Next Topic

Connecting to a Database

Now that a database handle has been allocated and associated with a session (by calling ctdbAllocDatabase()), the database handle can be connected to one of the databases in that session by calling ctdbConnect(), which connects the database handle to the database's files on disk. After that, the database is considered "active", and the database handle can be used to perform operations on that database.

Note that creating a new database is the exception to this rule; database creation does not require a database handle.

CTHANDLE pMyDatabase;

pMyDatabase = ctdbAllocDatabase(pMySession);

ctdbConnect(pMyDatabase, "MyFirstDatabase");

The first line above declares the database handle. The allocation of the handle (second line) links the handle to the session. Use ctdbConnect() (third line) to connect the database handle to the database using the database handle and the name of the database.

If the database doesn't exist, or exists but was dropped from the session, or was never added to the session, this call returns INOT_ERR (101). The best approach to avoid errors is to attempt to connect to the database, and if it doesn't exist, create it. The database path is not required to connect, since this information is stored inside the Session Dictionary. (The database path was provided to the session when the database was added to the session; see ctdbAddDatabase().)

When finished working with a database, disconnect it from your database handle using ctdbDisconnect() or disconnect all databases in a session from their handles with ctdbDisconnectAll(). When the database handle is no longer needed, free the allocated memory using ctdbFreeDatabase(). These steps are shown below, along with logging out from the session and freeing the session handle.

ctdbDisconnect(pMyDatabase);

ctdbLogout(pMySession);

ctdbFreeDatabase(pMyDatabase);

ctdbFreeSession(pMySession);

TOCIndex