Linux with the C language API to connect MySQL database

Source: Internet
Author: User
Tags exit include connect php and printf table name mysql database linux

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);
}

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.