Like PHP and Perl, MySQL also provides the API used by the C language.
The API for C code is published with MySQL. It is included in the Mysqlclient library and enables the C program to access the database.
Many of the 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's writing. You can find these examples in the clients directory of the MySQL source package.
Package
Make sure you have installed the necessary development environment, such as GCC, MySQL, and so on. The following is a list of packages that need 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
The following example connects the MySQL server on this computer and lists all the tables in the MySQL database:
The following is a reference fragment:
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 = ""; /* 此处改成你的密码 */
char *database = "mysql";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", 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);
}