- General Procedure for Building Client Programs
- Client 1—Connecting to the Server
- Client 2—Adding Error Checking
- Client 3—Making the Connection Code Modular
- Client 4—Getting Connection Parameters at Runtime
- Processing Queries
- Client 5—An Interactive Query Program
- Miscellaneous Topics
Miscellaneous Topics
This section covers several subjects that didn't fit very well into the progression as we went from client1 to client5:
Using result set data to calculate a result, after using result set metadata to help verify that the data are suitable for your calculations.
How to deal with data that are troublesome to insert into queries.
How to work with image data.
How to get information about the structure of your tables.
Common MySQL programming mistakes and how to avoid them.
Performing Calculations on Result Sets
So far we've concentrated on using result set metadata primarily for printing row data, but clearly there will be times when you need to do something with your data besides print it. For example, you can compute statistical information based on the data values, using the metadata to make sure the data conform to requirements you want them to satisfy. What type of requirements? For starters, you'd probably want to verify that a column on which you're planning to perform numeric computations actually contains numbers!
The following listing shows a simple function, summary_stats(), that takes a result set and a column index and produces summary statistics for the values in the column. The function also reports the number of missing values, which it detects by checking for NULL values. These calculations involve two requirements that the data must satisfy, so summary_stats() verifies them using the result set metadata:
The specified column must exist (that is, the column index must be within range of the number of columns in the result set).
The column must contain numeric values.
If these conditions do not hold, summary_stats() simply prints an error message and returns. The code is as follows:
void summary_stats (MYSQL_RES *res_set, unsigned int col_num) { MYSQL_FIELD *field; MYSQL_ROW row; unsigned int n, missing; double val, sum, sum_squares, var; /* verify data requirements */ if (mysql_num_fields (res_set) < col_num) { print_error (NULL, "illegal column number"); return; } mysql_field_seek (res_set, 0); field = mysql_fetch_field (res_set); if (!IS_NUM (field->type)) { print_error (NULL, "column is not numeric"); return; } /* calculate summary statistics */ n = 0; missing = 0; sum = 0; sum_squares = 0; mysql_data_seek (res_set, 0); while ((row = mysql_fetch_row (res_set)) != NULL) { if (row[col_num] == NULL) missing++; else { n++; val = atof (row[col_num]); /* convert string to number */ sum += val; sum_squares += val * val; } } if (n == 0) printf ("No observations\n"); else { printf ("Number of observations: %lu\n", n); printf ("Missing observations: %lu\n", missing); printf ("Sum: %g\n", sum); printf ("Mean: %g\n", sum / n); printf ("Sum of squares: %g\n", sum_squares); var = ((n * sum_squares) - (sum * sum)) / (n * (n - 1)); printf ("Variance: %g\n", var); printf ("Standard deviation: %g\n", sqrt (var)); } }
Note the call to mysql_data_seek() that precedes the mysql_fetch_row() loop. It's there to allow you to call summary_stats() multiple times for the same result set (in case you want to calculate statistics on several columns). Each time summary_stats() is invoked, it "rewinds" to the beginning of the result set. (This assumes that you create the result set with mysql_store_result(). If you create it with mysql_use_result(), you can only process rows in order, and you can process them only once.)
summary_stats() is a relatively simple function, but it should give you an idea of how you could program more complex calculations, such as a least-squares regression on two columns or standard statistics such as a t-test.
Encoding Problematic Data in Queries
Data values containing quotes, nulls, or backslashes, if inserted literally into a query, can cause problems when you try to execute the query. The following discussion describes the nature of the difficulty and how to solve it.
Suppose you want to construct a SELECT query based on the contents of the null-terminated string pointed to by name:
char query[1024]; sprintf (query, "SELECT * FROM my_tbl WHERE name='%s'", name);
If the value of name is something like "O'Malley, Brian", the resulting query is illegal because a quote appears inside a quoted string:
SELECT * FROM my_tbl WHERE name='O'Malley, Brian'
You need to treat the quote specially so that the server doesn't interpret it as the end of the name. One way to do this is to double the quote within the string. That is the ANSI SQL convention. MySQL understands that convention, and also allows the quote to be preceded by a backslash:
SELECT * FROM my_tbl WHERE name='O''Malley, Brian' SELECT * FROM my_tbl WHERE name='O\'Malley, Brian'
Another problematic situation involves the use of arbitrary binary data in a query. This happens, for example, in applications that store images in a database. Because a binary value may contain any character, it cannot be considered safe to put into a query as is.
To deal with this problem, use mysql_escape_string(), which encodes special characters to make them usable in quoted strings. Characters that mysql_escape_string() considers special are the null character, single quote, double quote, backslash, newline, carriage return, and Control-Z. (The last one occurs in Windows contexts.)
When should you use mysql_escape_string()? The safest answer is "always." However, if you're sure of the form of your data and know that it's okayperhaps because you have performed some prior validation check on ityou need not encode it. For example, if you are working with strings that you know represent legal phone numbers consisting entirely of digits and dashes, you don't need to call mysql_escape_string(). Otherwise, you probably should.
mysql_escape_string() encodes problematic characters by turning them into 2-character sequences that begin with a backslash. For example, a null byte becomes '\0', where the '0' is a printable ASCII zero, not a null. Backslash, single quote, and double quote become '\\', '\'', and '\"'.
To use mysql_escape_string(), invoke it like this:
to_len = mysql_escape_string (to_str, from_str, from_len);
mysql_escape_string() encodes from_str and writes the result into to_str, It also adds a terminating null, which is convenient because you can use the resulting string with functions such as strcpy() and strlen().
from_str points to a char buffer containing the string to be encoded. This string may contain anything, including binary data. to_str points to an existing char buffer where you want the encoded string to be written; do not pass an uninitialized or NULL pointer, expecting mysql_escape_string() to allocate space for you. The length of the buffer pointed to by to_str must be at least (from_len*2)+1 bytes long. (It's possible that every character in from_str will need encoding with 2 characters; the extra byte is for the terminating null.)
from_len and to_len are unsigned int values. from_len indicates the length of the data in from_str; it's necessary to provide the length because from_str may contain null bytes and cannot be treated as a null-terminated string. to_len, the return value from mysql_escape_string(), is the actual length of the resulting encoded string, not counting the terminating null.
When mysql_escape_string() returns, the encoded result in to_str can be treated as a null-terminated string because any nulls in from_str are encoded as the printable '\0' sequence.
To rewrite the SELECT-constructing code so that it works even for values of names that contain quotes, we could do something like this:
char query[1024], *p; p = strcpy (query, "SELECT * FROM my_tbl WHERE name='"); p += strlen (p); p += mysql_escape_string (p, name, strlen (name)); p = strcpy (p, "'");
Yes, that's ugly. If you want to simplify it a bit, at the cost of using a second buffer, do this instead:
char query[1024], buf[1024]; (void) mysql_escape_string (buf, name, strlen (name)); sprintf (query, "SELECT * FROM my_tbl WHERE name='%s'", buf);
Working With Image Data
One of the jobs for which mysql_escape_string() is essential involves loading image data into a table. This section shows how to do it. (The discussion applies to any other form of binary data as well.)
Suppose you want to read images from files and store them in a table, along with a unique identifier. The BLOB type is a good choice for binary data, so you could use a table specification like this:
CREATE TABLE images ( image_id INT NOT NULL PRIMARY KEY, image_data BLOB )
To actually get an image from a file into the images table, the following function, load_image(), does the job, given an identifier number and a pointer to an open file containing the image data:
int load_image (MYSQL *conn, int id, FILE *f) { char query[1024*100], buf[1024*10], *p; unsigned int from_len; int status; sprintf (query, "INSERT INTO images VALUES (%d,'", id); p = query + strlen (query); while ((from_len = fread (buf, 1, sizeof (buf), f)) > 0) { /* don't overrun end of query buffer! */ if (p + (2*from_len) + 3 > query + sizeof (query)) { print_error (NULL, "image too big"); return (1); } p += mysql_escape_string (p, buf, from_len); } (void) strcpy (p, "')"); status = mysql_query (conn, query); return (status); }
load_image() doesn't allocate a very large query buffer (100K), so it works only for relatively small images. In a real-world application, you might allocate the buffer dynamically based on the size of the image file.
Handling image data (or any binary data) that you get back out of a database isn't nearly as much of a problem as putting it in to begin with because the data values are available in raw form in the MYSQL_ROW variable, and the lengths are available by calling mysql_fetch_lengths(). Just be sure to treat the values as counted strings, not as null-terminated strings.
Getting Table Information
MySQL allows you to get information about the structure of your tables, using either of these queries (which are equivalent):
DESCRIBE tbl_name SHOW FIELDS FROM tbl_name
Both statements are like SELECT in that they return a result set. To find out about the columns in the table, all you need to do is process the rows in the result to pull out the information you want. For example, if you issue a DESCRIBE images statement from the mysql client, it returns this information:
+------------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+---------+------+-----+---------+-------+ | image_id | int(11) | | PRI | 0 | | | image_data | blob | YES | | NULL | | +------------+---------+------+-----+---------+-------+
If you execute the same query from your own client, you get the same information (without the boxes).
If you want information only about a single column, use this query instead:
SHOW FIELDS FROM tbl_name LIKE "col_name"
The query will return the same columns, but only one row (or no rows if the column doesn't exist).
Client Programming Mistakes To Avoid
This section discusses some common MySQL C API programming errors and how to avoid them. (These problems seem to crop up periodically on the MySQL mailing list; I didn't make them up.)
Mistake 1Using Uninitialized Connection Handler Pointers
In the examples shown in this chapter, we've called mysql_init() by passing a NULL argument to it. This tells mysql_init() to allocate and initialize a MYSQL structure and return a pointer to it. Another approach is to pass a pointer to an existing MYSQL structure. In this case, mysql_init() will initialize that structure and return a pointer to it without allocating the structure itself. If you want to use this second approach, be aware that it can lead to certain subtle problems. The following discussion points out some problems to watch out for.
If you pass a pointer to mysql_init(), it should actually point to something. Consider this piece of code:
main () { MYSQL *conn; mysql_init (conn); ... }
The problem is that mysql_init() receives a pointer, but that pointer doesn't point anywhere sensible. conn is a local variable and thus is uninitialized storage that can point anywhere when main() begins execution. That means mysql_init() will use the pointer and scribble on some random area of memory. If you're lucky, conn will point outside your program's address space and the system will terminate it immediately so that you'll realize that the problem occurs early in your code. If you're not so lucky, conn will point into some data that you don't use until later in your program, and you won't notice a problem until your program actually tries to use that data. In that case, your problem will appear to occur much farther into the execution of your program than where it actually originates and may be much more difficult to track down.
Here's a similar piece of problematic code:
MYSQL *conn; main () { mysql_init (conn); mysql_real_connect (conn, ...) mysql_query(conn, "SHOW DATABASES"); ... }
In this case conn is a global variable, so it's initialized to 0 (that is, NULL) before the program starts up. mysql_init() sees a NULL argument, so it initializes and allocates a new connection handler. Unfortunately, conn is still NULL because no value is ever assigned to it. As soon as you pass conn to a MySQL C API function that requires a non-NULL connection handler, your program will crash. The fix for both pieces of code is to make sure conn has a sensible value. For example, you can initialize it to the address of an already-allocated MYSQL structure:
MYSQL conn_struct, *conn = &conn_struct; ... mysql_init (conn);
However, the recommended (and easier!) solution is simply to pass NULL explicitly to mysql_init(), let that function allocate the MYSQL structure for you, and assign conn the return value:
MYSQL *conn; ... conn = mysql_init (NULL);
In any case, don't forget to test the return value of mysql_init() to make sure it's not NULL.
Mistake 2Failing to Test for a Valid Result Set
Remember to check the status of calls from which you expect to get a result set. This code doesn't do that:
MYSQL_RES *res_set; MYSQL_ROW row; res_set = mysql_store_result (conn); while ((row = mysql_fetch_row (res_set)) != NULL) { /* process row */ }
Unfortunately, if mysql_store_result() fails, res_set is NULL, and the while loop shouldn't even be executed. Test the return value of functions that return result sets to make sure you actually have something to work with.
Mistake 3Failing to Account for NULL Column Values
Don't forget to check whether or not column values in the MYSQL_ROW array returned by mysql_fetch_row() are NULL pointers. The following code crashes on some machines if row[i] is NULL:
for (i = 0; i < mysql_num_fields (res_set); i++) { if (i > 0) fputc ('\t', stdout); printf ("%s", row[i]); } fputc ('\n', stdout);
The worst part about this mistake is that some versions of printf() are forgiving and print "(null)" for NULL pointers, which allows you to get away with not fixing the problem. If you give your program to a friend who has a less-forgiving printf(), the program crashes and your friend concludes you're a lousy programmer. The loop should be written like this instead:
for (i = 0; i < mysql_num_fields (res_set); i++) { if (i > 0) fputc ('\t', stdout); printf ("%s", row[i] != NULL ? row[i] : "NULL"); } fputc ('\n', stdout);
The only time you need not check whether or not a column value is NULL is when you have already determined from the column's information structure that IS_NOT_NULL() is true.
Mistake 4Passing Nonsensical Result Buffers
Client library functions that expect you to supply buffers generally want them to really exist. This code violates that principle:
char *from_str = "some string"; char *to_str; unsigned int len; len = mysql_escape_string (to_str, from_str, strlen (from_str));
What's the problem? to_str must point to an existing buffer. In this example, it doesn'tit points to some random location. Don't pass an uninitialized pointer as the to_str argument to mysql_escape_string() unless you want it to stomp merrily all over some random piece of memory.