next up previous
Next: Loading Gt2 File Formatted Up: Implementation of a Relational Previous: Designing the Database

Communication with the Database

To demonstrate interfacing code written in C with the MySQL database, an example program was written illustrating the ability to connect to the database server, select databases, perform select and insert queries, loop through the results of queries, free query memory, etc. The source to this program can be found in Appendix A (Page [*]).

This program is composed of three main functions: main() which initializes the connection and calls the other two functions to perform queries, select_funct(), which performs a query passed to it via an argument and then returns data, and update_funct(), which performs data-modifying queries (such as updates, inserts, or dropping).

The program begins by calling mysql_connect() with the mysql, host, user, and password arguments. If host is null it is assumed to be localhost, if user is null it is assumed to be the current user, and if password is null assume no password. Then information on the connection type, id of the connection instance, and version of the server are given (showing that we are truly connected). The database on which we will be operating is then selected using the mysql_select_db() call. Once this has been accomplished, main() calls select_funct() with a query asking for the id, name, and other_info fields from the epoch table. select_funct() then submits the query and stores its results. mysql_num_fields() is then called for use in the loop which cycles through the rows of data returned. A for statement then loops through each column, retrieving and printing cells of data. Once this process has completed, mysql_free_result() is called to free the memory used by the mysql_store_result() call holding the returned data of the query. Assuming this query function finishes without running into a catastrophic error, control is returned to main() which then calls update_funct() with an insert query. update_funct() submits the query, obtains the number of rows affected through mysql_affected_rows(), and exits. Another select query is then performed to verify that a new record has been inserted, and finally a delete query is sent deleting the row which was inserted.


next up previous
Next: Loading Gt2 File Formatted Up: Implementation of a Relational Previous: Designing the Database
Chris Frost
1999-08-07