Step 4: Connecting Databases

The next step after opening a database is to create a connection to it as demonstrated in SDK samples samples/native/core/03_connect_*. Sample 03_connect_single_task demonstrates how, once the database is successfully opened, the function mco_db_connect() is called to create the database connection. Once a connection is successfully established, the connection handle can be passed to various application functions within the same thread to perform database operations. When completed, the function mco_db_disconnect() should always be called to close the connection before closing the database and terminating the application.

Sample 03_connect_multi_task demonstrates how a handle to an opened database can be used by multiple threads to create separate connections to the same database. Note that a common error is passing a single database connection to multiple threads. This must be avoided - every task (thread) must call mco_db_connect() to create its own separate connection.

Sample 03_connect_multi_process demonstrates how to detect if a database is already open by first calling mco_db_connect(). If the error code MCO_E_NOINSTANCE is returned, then the database has not yet been opened, so the application opens it and connects. Otherwise, the initial call to mco_db_connect() creates the connection and the application proceeds as desired. To see the sample in operation requires running the first process and then starting a second instance of the program (using a separate console).

Remember that once a database connection has been created, the application must close it by calling mco_db_disconnect() before closing the database.