MySQL :: MySQL 8.4 C API Developer Guide :: 5.4.58 mysql_real_connect() (original) (raw)

5.4.58 mysql_real_connect()

Description

mysql_real_connect() attempts to establish a connection to a MySQL server running onhost. Client programs must successfully connect to a server before executing any other API functions that require a valid MYSQL connection handler structure.

Specify the arguments as follows:

If your program uses CALL statements to execute stored procedures, theCLIENT_MULTI_RESULTS flag must be enabled. This is because each CALL returns a result to indicate the call status, in addition to any result sets that might be returned by statements executed within the procedure. BecauseCALL can return multiple results, process them using a loop that callsmysql_next_result() to determine whether there are more results.

CLIENT_MULTI_RESULTS can be enabled when you call mysql_real_connect(), either explicitly by passing theCLIENT_MULTI_RESULTS flag itself, or implicitly by passingCLIENT_MULTI_STATEMENTS (which also enablesCLIENT_MULTI_RESULTS).CLIENT_MULTI_RESULTS is enabled by default.

If you enable CLIENT_MULTI_STATEMENTS orCLIENT_MULTI_RESULTS, process the result for every call tomysql_real_query() ormysql_query() by using a loop that calls mysql_next_result() to determine whether there are more results. For an example, see Section 3.6.3, “Multiple Statement Execution Support”.

For some arguments, it is possible to have the value taken from an option file rather than from an explicit value in themysql_real_connect() call. To do this, call mysql_options() with the MYSQL_READ_DEFAULT_FILE orMYSQL_READ_DEFAULT_GROUP option before calling mysql_real_connect(). Then, in themysql_real_connect() call, specify the “no-value” value for each argument to be read from an option file:

If no value is found in an option file for an argument, its default value is used as indicated in the descriptions given earlier in this section.

Return Values

A MYSQL* connection handler if the connection was successful, NULL if the connection was unsuccessful. For a successful connection, the return value is the same as the value of the first argument.

Errors

Example

MYSQL mysql;

mysql_init(&mysql);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
{
    fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(&mysql));
}

By using mysql_options() the MySQL client library reads the [client] and[your_prog_name] sections in themy.cnf file. This enables you to add options to the [your_prog_name] section to ensure that your program works, even if someone has set up MySQL in some nonstandard way.