Accessing Databases using C

We direct you to the most useful MySQL C API programming tutorial and provide some additional notes here for trying the programs on a Raspberry Pi.

The MySQL server and client are easy to install. We used sudo apt-get install mysql-server python-mysqldb to obtain server, client (and the Python database API for experimentation). Give your server a memorable root password.

It is convenient to have one LXTerminal with a MySQL prompt and another with root privileges to compile the sources and to execute the programs. You can access the MySQL prompt with the command mysql -p -u root (which will create a request for your MySQL root password).

Our program names for the copied C code are version.c, createdb.c, create_cars.c, output_cars.c, create_writers.c, column_headers.c, multiple_statements.c, insert_image.c and get_image.c. All compile on the Raspberry Pi. Remember to change "root_pswd" in createdb.c to your memorable MySQL root password.

We compiled the first two source files with the commands provided and the other seven with these:

gcc create_cars.c -o create_cars -std=c99  `mysql_config --cflags --libs`
gcc output_cars.c -o output_cars -std=c99  `mysql_config --cflags --libs`
gcc create_writers.c -o create_writers -std=c99  `mysql_config --cflags --libs`
gcc column_headers.c -o column_headers -std=c99  `mysql_config --cflags --libs`
gcc multiple_statements.c -o multiple_statements -std=c99  `mysql_config --cflags --libs`
gcc insert_image.c -o insert_image -std=c99  `mysql_config --cflags --libs`
gcc get_image.c -o get_image -std=c99  `mysql_config --cflags --libs`

The version program gave this output:

MySQL client version: 5.5.41

The result of our command SHOW DATABASES; was

| Database           |
| information_schema |
| mysql              |
| performance_schema |
| testdb             |
4 rows in set (0.00 sec)
In the following line of output_cars.c, ? is the conditional operator.
printf("%s ", row[i] ? row[i] : "NULL");   

The programs have no code to handle command-line switches, so you can use int main() instead of int main(int argc, char **argv).

Programming - a skill for life!

How to apply your knowledge of Pascal when learning C/C++