Database Reference
In-Depth Information
...
if ( mysql_init ( mysql ) == NULL ) {
fprintf ( stderr , "Cannot Initialize MySQL" );
return 1 ;
}
...
The if statement here is testing whether a MySQL object can be initialized. If the initial-
ization fails, a message is printed and the program ends. The mysql_init() function
initializes the MySQL object using the MYSQL structure declared at the beginning of the
main function, which is called by convention, mysql . If C is successful in initializing
the object, it will go on to attempt to establish a connection to the MySQL server:
...
if (! mysql_real_connect ( mysql , "localhost" ,
"public_api" , "pwd_123" , "rookery" , 0 , NULL , 0 ))
{
fprintf ( stderr , "%d: %s \n " , mysql_errno ( mysql ),
mysql_error ( mysql ));
return 1 ;
}
...
The elements ofthe mysql_real_connect() function here are fairly obvious: first
the MySQL object is referenced; next the hostname or IP address; then the username and
password; and finally the database to use. For this example, we're using thepub-
lic_api@localhostuser account we created in the beginning of this chapter. The three re-
maining items are the port number, the socket filename, and a client flag, if any. Passing 0
and NULL values tells the function to use the defaults for these.
If the program cannot connect, it prints the error message generated by the server to the
standard error stream, along with the MySQL error number ( %d ), and finally a string ( %s )
containing the MySQL error message and then a newline ( \n ). It will get the error num-
ber from the mysql_errno() functionand the error message fromthe
mysql_error() function. If the program can connect without an error, though, it will
return 1 to indicate success and continue with the program.
Querying MySQL
The program so faronly makes a connection to MySQL. Now let's look at how you can
add code to the program to run an SQL statement with the C API.
Search WWH ::




Custom Search