Database Connections in C

A C application connects to the database (creates a database handle) by calling the mco_db_connect() API to create a connection handle. The database must have been previously opened, possibly in a different process if the database is in shared memory. If successful, mco_db_connect() returns a database connection that is used in subsequent calls to database APIs.

Note that an application must create a separate connection for each thread (task) that accesses the database; database connections cannot be shared between different threads or tasks.

Applications should disconnect from the database once the database connection is no longer needed to allow the database runtime to “de-allocate” internal memory used to maintain the connection. A C application disconnects from the database by calling mco_db_disconnect() passing the database connection handle. After disconnecting, all transaction handles created for this database instance become invalid. The database cannot be destroyed (closed) until all active connections are closed.

Example

Typical application code to connect to an in-memory database could look like the following:

     
    #define  DATABASE_SEGMENT_SIZE 300 * 1024
    #define  MEMORY_PAGE_SIZE 128
     
    int main(int argc, char* argv[])
    {
        MCO_RET            rc;
        mco_device_t       dev;
        mco_db_params_t    db_params;
        mco_db_h db;
        ...
        mco_runtime_start();
        ...
        dev.type       = MCO_MEMORY_CONV;                /* Set the device as a conventional memory device */
        dev.assignment = MCO_MEMORY_ASSIGN_DATABASE;     /* Assign the device as main database memory */
        dev.size       = DATABASE_SEGMENT_SIZE;          /* Set the device size */
        dev.dev.conv.ptr = (void*)malloc( DATABASE_SEGMENT_SIZE ); /* Allocate memory and set device pointer */
        ...
        mco_db_params_init ( &db_params );
        db_params.mem_page_size      = MEMORY_PAGE_SIZE; /* Set page size for the in-memory part */
        db_params.disk_page_size     = 0;                /* Set page size to zero to disable disk operations */
        db_params.db_max_connections = 1;                /* Set total number of connections to the database */
        ...
        rc = mco_db_open_dev(db_name, convdb_get_dictionary(), &dev, 1, &db_params );
        if ( MCO_S_OK == rc ) {
            mco_db_connect(db_name, &db);
            
            ...
            mco_db_disconnect(db);
            
            mco_db_close(db_name);
        }
        ...
        mco_runtime_stop();
    }