Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Client 5—An Interactive Query Program

Let's put together much of what we've developed so far and use it to write a simple interactive client. It lets you enter queries, executes them using our general purpose query handler process_query(), and displays the results using the process_result_set() display formatter developed in the preceding section.

client5 will be similar in some ways to mysql, although of course not with as many features. There are several restrictions on what client5 will allow as input:

  • Each input line must contain a single complete query.

  • Queries should not be terminated by a semicolon or by '\g'.

  • Commands such as quit are not recognized; instead, use Control-D to terminate the program.

It turns out that client5 is almost completely trivial to write (fewer than 10 lines of new code). Almost everything we need is provided by our client program skeleton (client4.c) and by other code that we have written already. The only thing we need to add is a loop that collects input lines and executes them.

To construct client5, begin by copying the client skeleton client4.c to client5.c. Then add to that the code for process_query(), process_result_set(), and print_dashes(). Finally, in client5.c, look for the line in main() that says the following:

/* do the real work here */

Then replace it with this while loop:

while (1)
{
char  buf[1024];
  fprintf (stderr, "query> ");          /* print prompt */
  if (fgets (buf, sizeof (buf), stdin) == NULL)  /* read query */
    break;
  process_query (conn, buf);            /* execute query */
}

Compile client5.c to produce client5.o, link client5.o with common.o and the client library to produce client5, and you're done! You have an interactive MySQL client program that can execute any query and display the results.

  • + Share This
  • 🔖 Save To Your Account