home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeManaging and Using MySQLSearch this book

19.2. Functions

mysql_list_processes

MYSQL_RES *mysql_list_processes(MYSQL *mysql)
Returns a MYSQL_RES structure containing information on all the threads currently running on the MySQL database server. (The term processes in the function name refers to the internal MySQL processes, or threads, not to any operating system-level process.) The information contained in the structure can be used with mysql_kill to remove faulty threads. Like all MYSQL_RES structures, the return value of this function must be freed with mysql_free_result. This function returns a null value in the case of an error.

The returned result set contains the information in the following order:

The MySQL process ID
This is the ID used with mysql_kill to kill a thread.

Username
The MySQL username of the user executing a thread.

Hostname
The location of the client running a thread.

Database
The current database for the client running a thread.

Action
The type of action last run in a thread. All SQL queries of any type show up as Query, so this will be the most common value.

Time
The amount of time taken (in seconds) to execute the last action in a thread.

State
The state of the current thread. This indicates whether the thread is active (currently executing a command) or idle.

Info
Any extra information about the thread. For SQL queries, this will contain the text of the query.

TIP: The information obtained from this function can also be obtained through an SQL query using the statement SHOW PROCESSLIST.

Example

MYSQL_RES *threads;
MYSQL_ROW row
threads = mysql_list_processes(&mysql);
 
row = mysql_fetch_row( threads );
printf("The ID of the first active thread is %d\n", row[0]);
mysql_odbc_escape_string

char *mysql_odbc_escape_string(MYSQL *mysql, char *result_string, unsigned long 
result_string_length, char *original_string, unsigned long original_string_length, 
void *parameters, char *(*extend_buffer))
Creates a properly escaped SQL query string from a given string. This function is intended for use with ODBC clients, and mysql_real_escape_string provides the same functionality with a simpler interface. This function takes the string given in the fourth argument (with the length given in the fifth argument, not including the terminating null character) and escapes it so that the resulting string (which is put into the address given in the second argument, with a maximum length given in the third argument) is safe to use as a MySQL SQL statement. This function returns a copy of the result string (the second argument). The seventh argument must be a pointer to a function that can be used to allocate memory for the result string. The function must take three arguments: a pointer to a set of parameters that control how the memory is allocated (these parameters are passed in as the sixth argument to the original function), a pointer to the result string, and a pointer to the maximum length of the result string.

Example

char *data = "\000\002\001";
int data_length = 3;
char *result;
int result_length = 5; /* We don't want the final string to be longer than 5.
 extend_buffer( ) is a function that meets the criteria given above. */
mysql_odbc_escape_string( &mysql, result, result_length, data, data_length,
   NULL, extend_buffer );
/* 'result' now contains the string '\\\000\002\001'
 (that is, a backslash, followed by ASCII 0, then ASCII 2 then ASCII 1. */
mysql_options

int mysql_options(MYSQL *mysql, enum mysql_option option, void *value)
Sets a connect option for an upcoming MySQL connection. This function must be called after a MYSQL structure has been initialized using mysql_init and before a connection has actually been established using mysql_real_connect. This function can be called multiple times to set more than one option. The options affect the upcoming connection. The value of the third argument depends on the type of option. Some options require a character string as an argument, while others take a pointer to an integer, or nothing at all. The options are as follows (the type of the third argument is given in parentheses after the option name):

MYSQL_INIT_COMMAND (char *)
Specifies an SQL query to execute as soon as the connection is established. This query is reexecuted if the connection is lost and automatically reconnected.

MYSQL_OPT_COMPRESS ()
Causes the connection to use a compressed protocol with the server to increase speed.

MYSQL_OPT_CONNECT_TIMEOUT (unsigned int *)
Specifies the number of seconds to wait before giving up on connecting to the server.

MYSQL_OPT_NAMED_PIPE ()
Causes the connection to use named pipes, as opposed to TCP, to connect to a local MySQL server running on Windows NT.

MYSQL_READ_DEFAULT_FILE (char *)
Specifies the name of the file to read for default options, in place of the default file my.cnf.

MYSQL_READ_DEFAULT_GROUP (char *)
Specifies the name of a section within the configuration file to read for the connection options, in place of the default client. See Chapter 4 for information about the configuration file options.

Example

MYSQL mysql;
mysql_init( &mysql );
/* Prepare this connection to use the compressed protocol, execute the
   query "SHOW tables" upon connection, and read addition options from the
   'startup' stanze in the file .mysqlrc */
mysql_options(&mysql, MYSQL_OPT_COMPRESS, 0 );
mysql_options(&mysql, MYSQL_INIT_COMMAND, "SHOW tables" );
mysql_options(&mysql, MYSQL_READ_DEFAULT_FILE, ".mysqlrc" );
mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "startup" );
/* Now it is time to call mysql_real_connect( ) to make the connection using
   these options */
mysql_real_connect

MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
                          const char *passwd, const char *db, uint port,
                          const char *unix_socket, uint client_flag)
Creates a connection with a MySQL database server. There are eight arguments to this function:

  • An initialized MYSQL structure, created with mysql_init.

  • The hostname or IP address of the MySQL database server (use an empty string or localhost to connect to the local MySQL server over a Unix socket).

  • The username used to connect to the database server (an empty string indicates that the Unix login name of the person running the client should be used).

  • The password used to authenticate the given user. If an empty string is used, only users with no passwords are checked for authentication. That is, if a user happened to have a password set to an empty string, he would never be authenticated.

  • The initial database selected when you connect (an empty string indicates that no database should be selected).

  • The port used to remotely connect to a MySQL database server over TCP. (0 may be used to accept the default port).

  • The filename of the Unix socket used to connect to a MySQL server on the local machine (an empty string may be used to accept the default socket).

  • Zero or more of a set of flags used under special circumstances:

    CLIENT_FOUND_ROWS
    When using queries that change tables, returns the number of rows found in the table, not the number of rows affected.

    CLIENT_IGNORE_SPACE
    Allows spaces after built-in MySQL functions in SQL queries. Traditionally, functions must be followed immediately by their arguments in parentheses. If this option is used, the function names become reserved words and cannot be used for names of tables, columns, or databases.

    CLIENT_INTERACTIVE
    Causes the server to wait for a longer amount of time (specified by the interactive_timeout server variable) before automatically breaking a connection. This is useful for interactive clients that do not allow the user to enter any data for significant periods of time.

    CLIENT_NO_SCHEMA
    Prevents the client from using the full database.table.column form to specify a column from any database.

    CLIENT_COMPRESS
    Causes the client to use compression when communicating with the server.

    CLIENT_ODBC
    Tells the server the client is an ODBC connection.

    CLIENT_SSL
    Tells the client to use SSL encryption to secure the connection. The server must have been compiled to support SSL.

Example

MYSQL *mysql;
mysql = mysql_init( NULL );
/* Connect to the server on the local host with standard options. */
if (! mysql_real_connect(&mysql, "localhost", "bob", "mypass", "", 0, "", 0))
{ print "Error connecting!\n";
  exit(1);
}
 
/* or... */
/* Connect to the server at my.server.com using a compressed, secure protocol */
if (! mysql_real_connect(&mysql, "my.server.com", "bob", "mypass",
                          "", 0, "", CLIENT_COMPRESS|CLIENT_SSL)) {
          print "Error connecting!\n";
          exit(1);
}
mysql_real_escape_string

unsigned long mysql_real_escape_string(MYSQL *mysql, char *result_string,
                                       char *original_string,
                                       unsigned long orginal_string_length)
Creates a properly escaped SQL query string from a given string. This function takes the string given in the third argument (with the length given in the fourth argument, not including the terminating null character) and escapes it so that the resulting string (which is put into the address given in the second argument) is safe to use as a MySQL SQL statement. This function returns the new length of the resulting string (not including the terminating null character). To be completely safe, the space allocated for the result string should be at least twice as big as the original string (in case each character has to be escaped) plus one (for the terminating null character).

TIP: This function is safe to use with binary data. The string can contain null characters or any other binary data. This is why it is necessary to include the length of the string. Otherwise, the MySQL library could not determine how long the string was if any null characters were present.

Example

# Properly escape a query that contains binary data.
char *data = "\002\001\000";
int original_length = 4 # 3 characters plus one for the null. 
char real_data[7]; # Twice as big as the original string (3) 
                   # plus one for the null.
int new_length;
 
new_length = mysql_real_escape_string(&mysql, data, real_data, original_length);
/* real_query can now be safely used in as a SQL query. */
/* The returned length is '4' since the only character that needed escaping
   was \000 (the null character) */
mysql_store_result

MYSQL_RES *mysql_store_result(MYSQL *mysql)
Reads the entire result of a query and stores it in a MYSQL_RES structure. Either this function or mysql_use_result must be called to access return information from a query. You must call mysql_free_result to free the MYSQL_RES structure when you are done with it.

The function returns a null value in the case of an error. The function also returns a null value if the query was not of a type that returns data (such as an INSERT or UPDATE query). If you receive a null pointer and are not sure if the query was supposed to return data or not, you can call mysql_field_count to find the number of fields the query was supposed to return. If zero, then it was a non-SELECT statement, and the pointer should be null. Otherwise, an error has occurred.

If the query was a SELECT-type statement, but happens to contain no data, this function will still return a valid (but empty) MYSQL_RES structure (it will not be a null pointer).

Example

MYSQL_RES results;
mysql_query(&mysql, "SELECT * FROM people");
results = mysql_store_result(&mysql);
/* 'results' should now contain all of the information from the 'people' table */
if (!results) { printf("An error has occurred!\n"); }

/* 'query' is some query string we obtained elsewhere, 
    we're not sure what it is... */
mysql_query(&mysql, query);
results = mysql_store_result(&mysql);
if (!results) { /* An error might have occurred, 
                   or maybe this is just a non-SELECT statement */
     if (! mysql_field_count(&mysql) ) { /* Aha! This is zero so it was 
                                            a non-SELECT statement */
               printf("No error here, just a non-SELECT statement...\n");
     } else {
               printf("An error has occurred!\n");
     }
}
mysql_use_result

MYSQL_RES *mysql_use_result(MYSQL *mysql)
Reads the result of a query row by row and allows access to the data through a MYSQL_RES structure. Either this function or mysql_store_result must be called to access return information from a query. Because this function does not read the entire data set all at once, it is faster and more memory efficient than mysql_store_result. However, when using this function, you must read all the rows of the data set from the server or else the next query will receive the leftover data. Also, you cannot run any other queries until you are done with the data in this query. Even worse, no other threads running on the server can access the tables used by the query until you are finished. For this reason, you should use this function only when you are certain you can read the data in a timely manner and release it. You must call mysql_free_result to free the MYSQL_RES structure when you are done with it.

The function returns a null value in the case of an error. The function also returns a null value if the query was not of a type that returns data (such as an INSERT or UPDATE query). If you receive a null pointer and are not sure if the query was supposed to return data or not, you can call mysql_field_count to find the number of fields the query was supposed to return. If zero, then it was a non-SELECT statement, and the pointer should be null. Otherwise, an error has occurred.

If the query was a SELECT-type statement, but happens to contain no data, this function still returns a valid (but empty) MYSQL_RES structure; i.e., it does not return a null pointer.

Example

MYSQL_RES results;
mysql_query(&mysql, "SELECT * FROM people");
results = mysql_store_result(&mysql);
/* 'results' will now allow access (using mysql_fetch_row) to the table
   data, one row at a time */


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.