The C API code to connect mysql on unix ( linux ) is being distributed with MySQL. It is the part of mysqlclient library and allows C programs to access a database.
Following packages needs to be compiled to access mysql from C/C++ on unix.
* mysql: MySQL client programs and shared library
* mysqlclient: Backlevel MySQL shared libraries (old libs)
* mysql-devel: Files for development of MySQL applications (a must have)
* mysql-server: Mysql server itself
* gcc, make and other development libs: GNU C compiler
How do I compile and link program against MySQL libs?
$ mysql_config --libs
$ mysql_config --cflags
$ gcc -o output-file $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs)
$ ./output-file
Sample Program
/* 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 = "PASSWORD"; /* set me first */
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);
}
Nice Information...Thanks..
ReplyDeleteJob Interview Questions
Hi Vikas,
ReplyDeleteThanks for highlighting this and indicating about Connecting MySQL with C++ on Linux with Screenshots where more study and thought is necessary.
New-ish to Linux. I have a few questions but it's best if I dedicate each question to a single thread.
What is the difference? Which is better: more stable, more supported, etc.?
Excellent tutorials - very easy to understand with all the details. I hope you will continue to provide more such tutorials.
Grazie,
Kevin