Linux uses C language APIs to connect to MySQL databases. like PHP and perl, MySQL also provides C language APIs.
C-code APIs are released along with MySQL. they are included in the mysqlclient library and allow C programs to access the database.
Many clients in the MySQL source package are written in C. if you are looking for examples of using these C APIs, you can look at the client writing method. you can find these examples in the clients Directory of the MySQL source package.
Software package
Make sure that you have installed the necessary development environment, such as gcc and mysql. The following is a list of software packages to be installed to compile a program (for example, Ubuntu ):
Mysql-client
Libmysqlclient15-dev and libmysqlclient15off
Mysql-server:
Gcc, make and other development libs
Example
In the following example, connect to the MySQL server of the local machine and list all the tables in the mysql database:
The following is a reference clip:
QUOTE:
/* Simple C program that connects to MySQL Database server */
# Include
# Include
Main (){
MYSQL * conn;
MYSQL_RES * res;
MYSQL_ROW row;
Char * server = "localhost ";
Char * user = "root ";
Char * password = "";/* change the password here */
Char * database = "mysql ";
Conn = mysql_init (NULL );
/* Connect to database */
If (! Mysql_real_connect (conn, server,
User, password, database, 0, NULL, 0 )){
Fprintf (stderr, "% sn", mysql_error (conn ));
Exit (1 );
}
/* Send SQL query */
If (mysql_query (conn, "show tables ")){
Fprintf (stderr, "% sn", mysql_error (conn ));
Exit (1 );
}
Res = mysql_use_result (conn );
/* Output table name */
Printf ("MySQL Tables in mysql database: n ");
While (row = mysql_fetch_row (res ))! = NULL)
Printf ("% s n", row [0]);
/* Close connection */
Mysql_free_result (res );
Mysql_close (conn );
}
Compile and connect programs
MySQL has a special script called mysql_config. it will compile the MySQL client for you and provide useful information for connecting to the MySQL server. you need to use the following two options.
1. -- libs option-Library and option required to connect to the MySQL client function library.
$ Mysql_config -- libs
Output:
-L/usr/lib64/mysql-lmysqlclient-lz-lcrypt-lnsl-lm-L/usr/lib64-lssl-lcrypto
2. -- cflags option-use necessary include file options and so on.
$ Mysql_config -- cflags
Output:
-I/usr/include/mysql-g-pipe-m64-D_GNU_SOURCE-D_FILE_OFFSET_BITS = 64-D_LARGEFILE_SOURCE-fno-strict-aliasing
You need to add the above two options to the compilation Command for the source file. therefore, to compile the above program, use the following command:
$ Gcc-o output-file $ (mysql_config -- cflags) mysql-c-api.c $ (mysql_config -- libs)
Run the compiled program:
$./Output. file