Name

mysql_connect( )

Synopsis

MYSQL *mysql_connect(MYSQL *mysql, const char *host, 
                     const char *user, cont char *password)

Use this to establish a connection to a MySQL server. The first argument is an object by mysql_init( ). The second argument for the function is the hostname. If NULL is given, the default of localhost is used. The third argument is the username for connecting and the fourth is the user’s password in plain text. The return value for the function, if successful, is a MYSQL structure and is saved to the variable named in the first argument. This variable should be used in subsequent functions to access the server. NULL is returned if the connection fails.

This function is deprecated in favor of mysql_real_connect( ). The mysql_close( ) function is used to end a connection:

int main( )
{
   MYSQL *mysql;
   const char *host = "localhost";
   const char *user = "russell";
   const char *password = "password";
   mysql = mysql_init(NULL);
   mysql_connect(mysql,host,user,password);
   ...
   mysql_close(mysql);
   exit(EXIT SUCCESS);
}

Notice that datatypes for the variables set up in the first few lines coincide with the data types shown in the function prototype. Instead of variables, the actual values may be given within the function. Each value must be contained within double quotes.

Get MySQL in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.