C API - Basic Usage

From Hashmysql
Jump to: navigation, search

Lesson 1: Connecting to a MySQL Server

We're going to start by writing a very simple program that connects to a given MySQL server. From there, we will build on this program to perform queries, fetch results, until we have a fully working MySQL-based program.

I am writing this C program on Redhat Linux 9, but it should compile on most Linux/Windows versions. I will assume you know enough C to be able to write and compile programs on your chosen system, so this tutorial will focus mainly on the MySQL aspects of programming.

Step 1:

The first thing we need to do is include the mysql.h header file. This header file gives us access to the MySQL C API. Without it, we wouldn't be able to use any of the MySQL API functions.

/* ===============================================================
   Lesson 1 - Connection to a MySQL Server
   =============================================================== */

#include <mysql.h>
#include <stdio.h>

This is the start of our C program. We have now included the mysql.h header, and the standard stdio.h header which we will be using functions from later.

Next, we need to start our main() function and setup the MYSQL struct for use:

int main()
        MYSQL mysql;

The MYSQL structure is used by the MySQL C API as a handle to one database connection. You will need to use this in every MySQL C API-enabled program that you write. There are other MySQL structures such as MYSQL_RES, MYSQL_ROW, etc, but we will go in to them at a later stage.

Along with the MYSQL structure, mysql_init() is a function that you will need to use in every program that you write. This function initializes and returns a new MYSQL object ready for use (or fails if it cannot allocate enough memory for it). This needs to be called before any other MySQL C API functions.

The next step, is to connect to our MySQL server.

For this, we use the mysql_real_connect() function. This function takes the following arguments:

mysql_real_connect(link, host, username, password, database, port, unix_socket, client_flag)

<...work in progress...>