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:
- For the first argument, specify the address of an existing
MYSQLstructure. Before callingmysql_real_connect(), callmysql_init() to initialize theMYSQLstructure. You can change a lot of connect options with themysql_options() call. SeeSection 5.4.54, “mysql_options()”. - The value of
hostmay be either a host name or an IP address. The client attempts to connect as follows:- If
hostisNULLor the string"localhost", a connection to the local host is assumed:
* On Windows, the client connects using a shared-memory connection, if the server has shared-memory connections enabled.
* On Unix, the client connects using a Unix socket file. Theunix_socketargument or theMYSQL_UNIX_PORTenvironment variable may be used to specify the socket name. - On Windows, if
hostis".", or TCP/IP is not enabled and nounix_socketis specified or the host is empty, the client connects using a named pipe, if the server has named-pipe connections enabled. If named-pipe connections are not enabled, an error occurs. - Otherwise, TCP/IP is used.
You can also influence the type of connection to use with theMYSQL_OPT_PROTOCOLorMYSQL_OPT_NAMED_PIPEoptions tomysql_options(). The type of connection must be supported by the server.
- If
- The
userargument contains the user's MySQL login ID. IfuserisNULLor the empty string"", the current user is assumed. Under Unix, this is the current login name. Under Windows ODBC, the current user name must be specified explicitly. See the Connector/ODBC section ofConnectors and APIs. - The
passwdargument contains the password foruser. IfpasswdisNULL, only entries in theusertable for the user that have a blank (empty) password field are checked for a match. This enables the database administrator to set up the MySQL privilege system in such a way that users get different privileges depending on whether they have specified a password.
Note
Do not attempt to encrypt the password before callingmysql_real_connect(); password encryption is handled automatically by the client API. - The
userandpasswdarguments use whatever character set has been configured for theMYSQLobject. By default, this isutf8mb4, but can be changed by calling mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "charset_name") prior to connecting. dbis the database name. Ifdbis notNULL, the connection sets the default database to this value.- If
portis not 0, the value is used as the port number for the TCP/IP connection. Note that thehostargument determines the type of the connection. - If
unix_socketis notNULL, the string specifies the socket or named pipe to use. Note that thehostargument determines the type of the connection. - The value of
client_flagis usually 0, but can be set to a combination of the following flags to enable certain features:CAN_HANDLE_EXPIRED_PASSWORDS: The client can handle expired passwords. For more information, seeServer Handling of Expired Passwords.CLIENT_COMPRESS: Use compression in the client/server protocol.CLIENT_FOUND_ROWS: Return the number of found (matched) rows, not the number of changed rows.CLIENT_IGNORE_SIGPIPE: Prevents the client library from installing aSIGPIPEsignal handler. This can be used to avoid conflicts with a handler that the application has already installed.CLIENT_IGNORE_SPACE: Permit spaces after function names. Makes all functions names reserved words.CLIENT_INTERACTIVE: Permitinteractive_timeout seconds of inactivity (rather thanwait_timeout seconds) before closing the connection. The client's sessionwait_timeout variable is set to the value of the sessioninteractive_timeout variable.CLIENT_LOCAL_FILES: EnableLOAD DATA LOCAL handling.CLIENT_MULTI_RESULTS: Tell the server that the client can handle multiple result sets from multiple-statement executions or stored procedures. This flag is automatically enabled ifCLIENT_MULTI_STATEMENTSis enabled. See the note following this table for more information about this flag.CLIENT_MULTI_STATEMENTS: Tell the server that the client may send multiple statements in a single string (separated by;characters). If this flag is not set, multiple-statement execution is disabled. See the note following this table for more information about this flag.CLIENT_NO_SCHEMA: Do not permit_dbname.tblname.colname_ syntax. This is for ODBC. It causes the parser to generate an error if you use that syntax, which is useful for trapping bugs in some ODBC programs.
From MySQL 8.0.32, theCLIENT_NO_SCHEMAflag is deprecated. Client programs can omit this flag and thedbargument to have the connection set the database value to the current (or default) database.CLIENT_ODBC: Unused.CLIENT_OPTIONAL_RESULTSET_METADATA: This flag makes result set metadata optional. Suppression of metadata transfer can improve performance, particularly for sessions that execute many queries that return few rows each. For details about managing result set metadata transfer, seeSection 3.6.7, “Optional Result Set Metadata”.CLIENT_SSL: Use SSL (encrypted protocol). Do not set this option within an application program; it is set internally in the client library. Instead, usemysql_options() before callingmysql_real_connect().CLIENT_REMEMBER_OPTIONS: Remember options specified by calls tomysql_options(). Without this option, ifmysql_real_connect() fails, you must repeat themysql_options() calls before trying to connect again. With this option, themysql_options() calls need not be repeated.
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:
- For
host, specify a value ofNULLor the empty string (""). - For
user, specify a value ofNULLor the empty string. - For
passwd, specify a value ofNULL. (For the password, a value of the empty string in themysql_real_connect() call cannot be overridden in an option file, because the empty string indicates explicitly that the MySQL account must have an empty password.) - For
db, specify a value ofNULLor the empty string. - For
port, specify a value of 0. - For
unix_socket, specify a value ofNULL.
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
- CR_CONN_HOST_ERROR
Failed to connect to the MySQL server. - CR_CONNECTION_ERROR
Failed to connect to the local MySQL server. - CR_IPSOCK_ERROR
Failed to create an IP socket. - CR_OUT_OF_MEMORY
Out of memory. - CR_SOCKET_CREATE_ERROR
Failed to create a Unix socket. - CR_UNKNOWN_HOST
Failed to find the IP address for the host name. - CR_VERSION_ERROR
A protocol mismatch resulted from attempting to connect to a server with a client library that uses a different protocol version. - CR_NAMEDPIPEOPEN_ERROR
Failed to create a named pipe on Windows. - CR_NAMEDPIPEWAIT_ERROR
Failed to wait for a named pipe on Windows. - CR_NAMEDPIPESETSTATE_ERROR
Failed to get a pipe handler on Windows. - CR_SERVER_LOST
If connect_timeout > 0 and it took longer thanconnect_timeout seconds to connect to the server or if the server died while executing theinit-command. - CR_ALREADY_CONNECTED
TheMYSQLconnection handler is already connected.
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.