Connect to MySQL using C language in Linux

Source: Internet
Author: User

First, ensure installation:1: install MySQL: sudo apt-get install mysql-server mysql-client 2: install MySQL development kit: sudo apt-get install libmysqlclient15-dev the header files that need to be used will appear in/usr/include/mysql/
There are two steps to connect a C language to a MySQL database: 1. Use the mysql_init function to initialize a connection handle structure. The Function Definition of mysql_init is as follows:

MYSQL * mysql_init(MYSQL *);
Generally, if NULL is passed to this routine, it returns a pointer pointing to the new connection handle structure. If an existing structure is passed, it will be reinitialized. This routine returns NULL when an error occurs.

2. Currently, only a structure is allocated and initialized for the actual connection. You still need to use mysql_real_connect to provide parameters for a connection,
Function Definition of mysql_real_connect:
MYSQL* mysql_real_connect(MYSQL* connection,const char *server_host,const char *sql_user_name,const char *sql_password,const char *db_name,unsigned int port_number,const char *unix_socket_name,unsigned int flags);

The pointer connection must point to the structure initialized by mysql_init.

Note that server_host can be either a host name or an IP address. If the connection is local, you can set localhost for optimization.

SQL _user_name and SQL _password have the same meaning as their literal meanings. If the login name is NULL, assume that the login name is the logon ID of the current Linux User. If the password is NULL, assume that the password is NULL.

Port_number and unix_socket_name should be 0 and NULL respectively, unless you change the default settings for MySQL installation. They will use the appropriate value by default.

Finally, the flags parameter is used to perform OR operations on some defined bit modes to change some features of the Protocol.

If the connection fails, NULL is returned. The mysql_error function provides helpful information.

3. After using the connection, you must call the mysql_close function before exiting the program;

Function Definition of mysql_close:

void mysql_close(MYSQL *connection);
The connection will be closed.

Example of connecting to MySQL:
# Include <stdio. h> # include <stdlib. h> # include "mysql. h "int main (int argc, char * argv []) {MYSQL * conn; // Step 1: Initialize the connection handle conn = mysql_init (NULL ); if (conn = NULL) {// if NULl is returned, printf ("mysql_init failed! \ N "); return EXIT_FAILURE;} // Step 2: The actual connection parameters are: conn connection handle, host is the host or address of MySQL, user name, password, database_name database name, followed by the default conn = mysql_real_connect (conn, "host", "user", "password", "database_name", 0, NULL, 0 ); if (conn) {// printf ("Connection success! \ N ");} else {printf (" Connection failed! \ N ") ;}// Step 3: Close the connection mysql_close (conn); return 0 ;}

Compile and run:
gcc -I/usr/include/mysql test.c -L/usr/lib/mysql -lmysqlclient -o app
Error Handling

Two functions for error handling:

// Return the error code unsigned int mysql_errno (MYSQL * connection); // return the error details char * mysql_error (MYSQL * connection );
Note: When you call conn = mysql_real_connect (...), you will encounter a problem because it returns a NULL pointer in case of failure and does not provide an error code. However, if the handle is used as a variable, it can still be processed even if mysql_real_connect fails.
# Include <stdio. h> # include <stdlib. h> # include "mysql. h "# include" errmsg. h "# include" mysqld_error.h "void Error (MYSQL * conn) {printf (" Connection error % d: % s \ n ", mysql_errno (conn ), mysql_error (conn);} int main (int argc, char * argv []) {MYSQL conn; // It is a variable instead of a pointer mysql_init (& conn ); // note the URL & if (mysql_real_connect (& conn, "192.168.137.246", "root", "123456", "test", 0, NULL, 0 )) {printf ("Connection success ! \ N "); mysql_close (& conn);} else {fprintf (stderr," Connection failed! \ N "); if (mysql_errno (& conn) {fprintf (stderr," Connection error % d: % s \ n ", mysql_errno (& conn ), mysql_error (& conn) ;}return EXIT_SUCCESS ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.