Previous | Table of Contents | Next
Chapter 3. Connecting to the Database
In order to interact with the database, you must first open a connection
handle to the database server. The handle to the database is called
MYSQL and is the structure you must use for subsequent calls
to the database.
Here is a sample snippet of code to connect to the database.
#include "mysql.h"
#include <stdio.h>
#include <stdlib.h>
MYSQL mysql;
void exiterr(int exitcode)
{
fprintf( stderr, "%s\n", mysql_error(&mysql) );
exit( exitcode );
}
int main()
{
if (!(mysql_connect(&mysql,"host","username","password")))
exiterr(1);
if (mysql_select_db(&mysql,"payroll"))
exiterr(2);
/*...*/
}
The second call, mysql_select_db allows you to define which
database you are using. You must call this before you continue to interact
with the database.
For the connect call, you may specify any argument as NULL. If you specify
the host as NULL, the localhost is assumed. If the user is NULL,
then the current user is assumed. If password is NULL, then only users in
the user table without a password entry will be checked for a match.
The error call mysql_error returns a string which explains the
last error that occurred. More about MySQL errors will be discussed later.
Previous | Table of Contents | Next