O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Support Functions

Our example includes three simple helper functions to support its work. The first initializes everything:

MySQL * connection, mysql;
  
int init_api(  ) {
    mysql_init(&mysql);
    connection = mysql_real_connect(&mysql, "localhost", "orausr",
                                    "orapw", "oradb", 0, 0, 0);
    if( connection == NULL ) {
        return -1;
    }
    else {
        return 0;
    }
}

This function does the MySQL initialization we covered earlier in the chapter. It specifically establishes a connection to the database. If any error occurs while making the connection, it returns -1.

The second support function is the opposite of the initialization function; it closes everything:

void close_api(  ) {
    if( connection != NULL ) {
        mysql_close(connection);
        connection = NULL;
    }
}

The last support function will be used many times in the example. It returns a message for the last error.

char *error;
  
char *get_error(  ) {
    return error;
}

Any time the API encounters an error condition, it sets the error variable to the appropriate error message. Applications calling this API therefore call this function to retrieve the last error message. You should always copy any error messages into storage managed by your application if you wish to save them for later use.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required