MySQL Chapter Four (C API)
Documentation Version: 0.95
MySQL Version: 3.20.29
Overview
This chapter documents the C Application Programming Interface (API) supplied with the MySQL database system. The API supports a rich assortment of functions that allow complete access to the MySQL database engine from a client program, regardless of whether it is running locally or on a Remote system.
Preparation
You will need to include the mysql.h header file at the top of your c propr_
#include "mysql.h"
You Will Also Need to Link in The Math (for Encryption) and MySQLCLIENT LIBRARIES:
$ cc -i / usr / include / mysql -l / usr / lib / mysql myapp.c -o myapp -lm -lmysqlclient
The include files are type.
If you have a memory leak in your client you can compile with the --with-debug = yes option. This will cause the client code to use the 'safe_malloc' package in the MySQL client library. You would call TERMINATE (stdout) or MY_END (1) IN Your Client Application Before Exiting to Get A List of All Memory Leaks. Check The File MySys / SafeMalloc.c in The Source Distribution for Further Details.
Following is a sample MySQL client program that would simply perform a SELECT and then display all returned rows on standard output. While not all API functions are included, it should give you an idea of the typical client program layout.
#include
#include
#include "mysql.h"
Mysql mysql;
Mysql_res * res;
Mysql_row rotion;
Void Exiterr (int exitcode)
{
FPRINTF (stderr, "% s / n", mysql_error (& mysql));
EXIT (EXITCODE);
}
int main ()
{
UINT I = 0;
IF (! (& Mysql_Connect (& Mysql, "Host", "UserName", "PASSWORD"))) EXITERR (1);
IF (MySQL_SELECT_DB (& mysql, "payroll")))
EXITERR (2);
IF (Mysql_Query (& mysql, "SELECT NAME, RATE FROM EMP_MASTER))
EXITERR (3);
IF (! (rs = mysql_store_result (& mysql)))))
EXITERR (4);
While ((rot = mysql_fetch_row (res))) {
For (i = 0; i Printf ("% s / n", row [i]); } IF (! mysql_eof (res)) EXITERR (5); MySQL_Free_Result (res); MySQL_Close (& mysql); } Client functions The MySQL API uses a MYSQL data structure (defined in mysql.h) to establish a connection with the database engine. You may set up multiple connections from a single client program, however, each connection must be assigned to its own separate MYSQL structure. After a successful query, if data is to be returned to the client, the result set must be transferred via either the mysql_store_result or mysql_use_result functions. Both of these functions store the result set in a MYSQL_RES structure. The difference is that mysql_store_result reads the entire result set into memory on the client, where mysql_use_result instructs the client to retrieve a row dynamically from the server with each call to mysql_fetch_row. Keep in mind, however, that mysql_use_result ties up server resources and thus should not be used for interactive applications where user actions are often unpredictable and could result in extended delays. Note also that you may have only one connection open that uses mysql_user_result, and it must be the most recently created one. An additional consideration is the fact that by default the mysqld process will close the Connection After Thirty Seconds of iDLE TIME. Data Retrieved from the result set with mysql_fetch_row is placed Into a mysql_row structure, Which is simply an array of pointers to the beginning beginning of each field. MySQL_AFFECTED_ROWS Synopsis: INT mysql_affected_rows (mysql * mysql) Description: Retrieves the number of rows affected by the last update, delete or insert. Return Value: An integer> 0 indicating the number of changed / retrieved rows. Zero if no records matched the WHERE clause in an UPDATE or DELETE. -1 if the query returned an error, for example and attempt was made to add a duplicate primary key during an INSERT. EXAMPLE: Mysql_Query (& mysql, "INSERT INTO GL_TRANSACT (Acctnbr, Amount) VALUES (12345, 651.30)") IF (MySQL_AFFECTED_ROWS (& mysql) <0) FPRINTF (stderr, "attempted to address;); MySQL is optimized for the 'delete all records in a table' case. A side effect of this optimization is that MySQL will return zero for the number of rows affected in this situation. Doing a 'select count (*) from the_table' before deleting all records will give you a value for the number of rows affected, though this value may change between the SELECT and and DELETE since MySQL 3.20.X does not support table locking. This is fixed in version 3.21.X MySQL_Close Synopsis: Void mysql_close (mysql * mysql); Description: Closes a previously.com. mysql_close must be called after completing all operations performed via the MySQL connection. If not done, the thread created by mysql_connect will linger until the built-in timeout is reached. On a busy server this can quickly eat a lot of memory, although it should Take Very Little CPU TIME. If a connection is closed before a running query has completed, the query will continue until it attempts to return any part of the result set to the client. It will then die upon noticing that the connection is no longer active.The default timeout is 30 Seconds for an Active Query and 8 Hours for An Open Connection. Return Value: NONE. MySQL_CONNECT Synopsis: Mysql * mysql_connect (mysql * mysql, const char * user, const char * passwd) Description: Attempts to establish a connection to a MySQL database engine running on host The value of host may be either a hostname or an IP address The user parameter contains the user's MySQL login ID, and the passwd parameter contains the password for user NOTE...: DO NOT Attempt to Encrypt Passwd Before Calling MySQL_Connect. Encryption is Handled Automatically by The Client API. If host is NULL, 'localhost' is assumed. If user is NULL, 'current user' is assumed. Under Windows ODBC, the current user must be explicitly specified. Under Unix the current login ID is assumed. If password is NULL then only records in the user table without a password entry will be checked for a match. This allows the db-admin to setup the MySQL privilege system in such a way that a user gets different privileges depending on whether they have specified a password or not. MySQL_Connect Must Complete Success BEFORE ANY Action Is Allowed To Be Performed on a Database. You may optionally specify the first argument of mysql_connect to be (MYSQL *) 0 This will force the C API to automatically alloc memory for the connection structure and free it on close. The downside of this approach is that you can not retrieve an error Message from MySQL_Connect When You Use this option.Return Value: Mysql if The Connection Was Successful. Null if unsuccessful. EXAMPLE: Mysql * mysql; IF ((mysql = malloc (sizeof (mysql)))! = NULL) { IF (! (Mysql, "PR_SERVER", "jqpublic", "mypasswd")))))))) { Free (mysql); Exit (1); } } Free (mysql); MySQL_CREATE_DB Synopsis: INT mysql_create_db (mysql * mysql, const char * dB); Description: Creates The Database Named in db on the machine Pointed to by MySQL. The MySQL Connection Must Have Been Made with a User ID That Has Create Privileges. (Refer to Chapter 5 for more detils on user privilege Return Value: ZERO IF The Database Was SuccessFully Created. Non-Zero if An error Occurred. The Error Message May Be Retrieved by Calling MySQL_ERROR. MySQL_DATA_SEEK Synopsis: Void mysql_data_seek (mysql_res * res, uint offset); Description: Seeks to an arbitrary row in a query result set. May not be used in conjunction with mysql_use_result Return Value: None MySQL_DROP_DB Synopsis: INT mysql_drop_db (mysql * mysql, const char * dB); Description: Drop the database named in db from the machine pointed to by mysql. The connection must have been made with a user ID that has drop privileges for the specified database. (Refer to chapter 6 for more details on user privileges.) Return Value: ZERO IF The Database WAS Success, Dropped. Non-Zero if An error Occurred. The Error Message May Be Retrieved by Calling MySQL_ERROR.MYSQL_EOF Synopsis: INT mysql_eof (mysql_res *) Description: Returns a value! = 0 if the last call to MySQL_FETCH_ROW RETURNED NOTHING BECAUSE The End of The Result Set Has Been Reached. MySQL_ERROR Synopsis: Char * mysql_error (mysql * mysql) Description: The error message, if any, returned by the last mysql function call on connections Mysql. An Empty String Will Be Returned If No Error Occurred. MySQL_FETCH_FIELD Synopsis: MySQL_Field * mysql_fetch_field (mysql_res * handle); Description: Find Out What Type A Table Field IS. MySQL_FETCH_LENGTHS Synopsis: Unsigned int * mysql_fetch_lengths (mysql_res * mysql) Description: RETURns The Length of All Column in a Query Result Set. If Plan on Retrieving Data That Contains A / 0 You Must Use this function to get the actual length of the field value. MySQL_FETCH_ROW Synopsis: MySQL_ROW MYSQL_FETCH_ROW (mysql_res * mysql); Description: Fetch the 'Next' Row in The Query Result. Will Return A Null Pointer When All Rows Have Been Retrieved. MySQL_Field_seek Synopsis: Void mysql_field_seek (MySQL_RES * Result, INT Field) Description: Put The Column Cursor On Column Number Field, Which Should Be within the Range from 0 to MySQL_NUM_FIELDS (mysql_res *) - 1 MySQL_FREE_RESULT Synopsis: Void mysql_free_result (mysql_res * result); Description: Free Memory Used to Store A Query Result. SHOULD BE CALLED WHENEER You Have Finished Using The Results of a MySQL_Store_Result () CALL MySQL_GET_CLIENT_INFO Synopsis: Char * mysql_get_client_info (void); Description: THIS FUNCTION SIMPLY RETURns A STRING Containing Version Information For the Client Library Currently in Use.mysql_get_host_info Synopsis: Char * mysql_get_host_info (mysql * mysql); Description: Returns Name of Host (Same as The Host Argument to MySQL_CONNECT). MySQL_GET_PROTO_INFO Synopsis: INT mysql_get_proto_info (mysql * mysql); Description: Get protocol version used by connection. MySQL implements dynamic protocols based on client capabilities. In version 3.20.X this does not really do anything, but in future versions it will for example allow one client to connect using the current protocol, while another connects Using Encryption and Compression. MySQL_GET_SERVER_INFO Synopsis: Char * mysql_get_server_info (mysql * mysql); Description: Returns The Version Number of the Server. MySQL_INSERT_ID Synopsis: INT mysql_insert_id (mysql * mysql) Description: Returns ID generated for auto_increment Field on Result Variable 'res'. MySQL_LIST_DBS Synopsis: Mysql_res * mysql_list_dbs (mysql * mysql, const char * wild); Description: Provided to Ease Porting of MSQL Applications. Similar to doing 'show databases [like wild-card]' as a query. MySQL_LIST_FIELDS Synopsis: Mysql_res * mysql_list_fields (mysql * mysql, const char * table, const char * wild); Description: Provided to Ease Porting of MSQL Applications. Similar to doing 'show fields [from table] [from database] [Like Wild-card]' in a query. mysql_list_processes Synopsis: MySQL_RES * mysql_list_processes (mysql * mysql); Description: Get A List of the Thread Currently Running on The My Must Have Process Privileges. MySQL_LIST_TABLES Synopsis: Mysql_res * mysql_list_tables (mysql * mysql, const char * wild); Description: Provided to Ease Porting of MSQL Applications. Similar to doing 'show tables [from database]' as a query. MySQL_NUM_FIELDS Synopsis: INT mysql_num_fields (mysql_res * result); Description: This Macro Returns The Number of Columns (Fields) IN A Query Result. EXAMPLE: Mysql mysql; Mysql_res * result; Int fields; IF (Mysql_Query (& mysql, "SELECT * FROM EMP_MASTER") == 0) { Result = mysql_store_Result (& mysql); IF (Result! = NULL) { Fields = mysql_num_fields (result); Printf ("Retrieved% U Fields / N", Fields); } Else Printf ("Query FaileD / N"); } Else Abort (); See Also: Mysql_list_dbs, mysql_list_fields, mysql_list_processes, mysql_list_tables, mysql_store_result, mysql_use_result MySQL_NUM_ROWS Synopsis: INT mysql_num_rows (mysql_res * result); Description: This macro returns the number of rows returned by the last mysql_list_dbs, mysql_list_fields, mysql_list_processes, mysql_list_tables or mysql_store_result. EXAMPLE: Mysql mysql; Mysql_res * result; int ROWS; IF (Mysql_Query (& mysql, "SELECT * FROM EMP_MASTER") == 0) { Result = mysql_store_Result (& mysql); IF (Result! = NULL) { ROWS = mysql_num_rows (result); Printf ("Retrieved% U ROWS / N", ROWS); } Else Printf ("Query FaileD / N"); } Else Abort (); See Also: Mysql_list_dbs, mysql_list_fields, mysql_list_processes, mysql_list_tables, mysql_store_result, mysql_use_result MySQL_QUERY Synopsis: INT mysql_query (mysql * mysql, const char * query); Description: Executes the SQL query pointed to by query mysql_num_rows will give on the database pointed to by mysql. This function will return zero if the query executed properly. A non-zero result indicates an error. A call to mysql_error will retrieve the error message.Calling You the number of rows returned by the query. If you have an auto_increment field in the table beding update, you are doing an insert, you can find the newly assigned field value by checking mysql_insert_id. MySQL_Real_Query Synopsis: INT mysql_real_query (mysql * mysql, const char * query, uint length); Description: This function is called by mysql_query after it Does a strlen filter call to calculate the length of the query string. It could be used if your program allocates a fixed buffer for the query string. You'll Have to Use this function if you have data with un-escaped / 0 values. MySQL_RELOAD Synopsis: INT mysql_reload (mysql * mysql); Description: ................................. Requires User to Have Reload Privileges. MySQL_SELECT_DB Synopsis: INT mysql_select_db (mysql * mysql, const char * dB); Description: Attempt to connect to the database pointed to by db, on the machine pointed to by mysql. The MySQL database engine on the server will use the login and password contained in mysql to authenticate the connection. A successful call to mysql_connect is necessary before mySQL_SELECT_DB CAN be used. In General MySQL_SELECT_DB MUST BE CALLED SUCCESSFULLY Before Attempting to Query A Database. The Exceptions Are Queries Such as The Following. Show Databases Like 'a%'; SELECT 1 1; #select without using Tables.mysql_shutdown Synopsis: INT mysql_shutdown (mysql * mysql); Description: SHUT DOWN A MYSQL Database Engine. User Must Have Shutdown Privileges. MySQL_STAT Synopsis: Char * mysql_stat (mysql * mysql); Description: Returns the info similar to 'mysqladmin version' as a character string. This includes uptime in seconds, running threads, questions, reloads and open tables information. This is essentially the same as the mysqladmin programs stat option. MySQL_STORE_RESULT Synopsis: Mysql_res * mysql_store_result (mysql * mysql); Description: Reads the result to the client. You must use this or mysql_use_result () to get the result from the server. You must always use mysql_store_result () or mysql_use_result () after you have executed a successful query. MySQL_Store_Result () Returns Null On Error or if The Statement Didn't Return Any Data. You Can Cack for Errors with: IF (! (= mysql_store_result (& mysql)) && mySQL_NUM_FIELDS (& mysql)) FPUTS (MySQL_ERROR (& mysql), stderr); A call to mysql_free_result () Must Be Made When You're Done to Free Memory. MySQL_USE_RESULT Synopsis: Mysql_res * mysql_use_result (mysql * mysql); Description: The same as mysql_store_result (), except that the result is fetched dynamically from the server for each 'mysql_fetch_row ()'. This should not be used on interactive applications since it ties up the server. This helps to hold down the memory usage on the Client Side.