Use Capi to connect to a mysql database development instance

Source: Internet
Author: User
Tags mysql connect
1. download the mysqlcconnector installation package. There are two methods: 1. Download the tar file and put lib, include, and bin in the corresponding directory of usrlocal; 2. you can also configure the additional directory of the Linked Library: sudovietcld. so. add the lib directory of your connector to the conf file; 3. it seems that sudoapt can also be used.

1. download the installation package of mysql c connector. There are two methods: 1. Download the tar file and put lib, include, and bin in the corresponding directory of/usr/local; 2. you can also configure the additional directory of The Link Library: sudo vi/etc/ld. so. add the lib directory of your connector to the conf file; 3. it seems that sudo apt can also be used.

1. Download the mysql c connector installation package. There are two methods:

1. Download the tar file and put lib, include, and bin in the directory corresponding to/usr/local;

2. You can also configure the additional directory of The Link Library: add the lib directory of your connector to The sudo vi/etc/ld. so. conf file;

3. It seems that sudo apt-get install libmysqclient-dev can also be used.

For c ++, it seems that sudo apt-get install libmysql ++-dev

2. Edit the C program to use mysql c api: My program is as follows:# Include <mysql. h> # include <stdio. h> # include <stdlib. h> # include <string. h> static void output_error (MYSQL * mysql); int main (int argc, char * argv []) {MYSQL mysql; MYSQL_RES * result; MYSQL_ROW row; MYSQL_FIELD * fields; const char * host = "localhost"; const char * user = "root"; const char * password = "root"; const char * database = "test "; const int port = 3306; const char * socket = NULL; const int flag = 0; con St char * SQL; int num_fields; unsigned long * lengths; int I; // initialize the database if (! Mysql_init (& mysql) {output_error (& mysql);} printf ("mysql initialized successfully! /N "); // connect to the database; if (! Mysql_real_connect (& mysql, host, user, password, database, port, socket, flag) {output_error (& mysql);} printf ("mysql connect successfully! /N "); printf ("/n/nthe content of the table data in the database test/n "); printf (" ---------------------------------------------------------/n "); // do the select query on the database; SQL = "select * from data"; // printf ("% d: % d/n", sizeof (SQL ), strlen (SQL); // 4:18 sizeof (SQL): the size of point -- (4); strlen (SQL): if (mysql_real_query (& mysql, SQL, strlen (SQL) {output_error (& mysql) ;}// fetch The result set of the query! Result = mysql_store_result (& mysql); if (result) {fields = mysql_fetch_fields (result); // fetch the struct of result num_fields = mysql_num_fields (result ); // fetch the number of result fields; // lengths = mysql_fetch_lengths (result); for (I = 0; I <num_fields; I ++) {printf ("% s/t", fields [I]. name);} printf ("/n"); while (row = mysql_fetch_row (result) {for (I = 0; I <num_fields; I ++) {printf ("% s/t", row [I]);} printf ("/n ");} // release the result of set for release the memorymysql_free_result (result);} else {output_error (& mysql);} printf ("/n records/n "); // close the connetion to the databasemysql_close (& mysql); return 0;} static void output_error (MYSQL * mysql) {fprintf (stderr, "errorno: % d/n ", mysql_errno (mysql); fprintf (stderr, "error info: % s/n", mysql_error (mysql); exit (1 );}

3. Compile the link and test:

Wzb @ wzb-desktop :~ /Test $ gcc-o db_test db_test.c-lmysql wzb @ wzb-desktop :~ /Test $./db_testmysql initialized successfully! Mysql connect successfully! The content of the table data in the database test has idnodeIddataflagtime1 0 0 0 18:19:40 2 1 1 2 18:29:05 too wzb @ wzb-desktop :~ /Test $

Note:-lmysql

4. develop several useful commands for mysql c: ldd, mysql_config, file, nm

Ldd: outputs the dependency on the dynamic library, that is, the dependent dynamic library information;

Mysql_conf: Obtain mysql configuration Development Information: mysql_config -- libs

Let's take a look at the output of these commands:

Wzb @ wzb-desktop :~ /Test $ ldd db_testlinux-gate.so.1 => (0x00f40000) libmysql. so.16 =>/usr/local/lib/libmysql. so.16 (0x0020f000) libc. so.6 =>/lib/tls/i686/cmov/libc. so.6 (0x006bf000) libpthread. so.0 =>/lib/tls/i686/cmov/libpthread. so.0 (0x004e4000) libm. so.6 =>/lib/tls/i686/cmov/libm. so.6 (0x00110000)/lib/ld-linux.so.2 (0x00af6000) wzb @ wzb-desktop :~ /Test $ file db_testdb_test: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, not strippedwzb @ wzb-desktop :~ /Test $ nm 1_d _ DYNAMIC08049ec0 d _ 1_r _ 1_w _ 1_d _ CTOR_END _ 08049dd0 d _ CTOR_LIST _ 08049ddc d _ DTOR_END _ 08049dd8 d _ _ DTOR_LIST _ 08048dcc r _ FRAME_END _ 08049de0 d _ JCR_END _ 08049de0 d _ JCR_LIST _ 08049f24 A _ 1_d _ blank t _ blank _ _ do_global_dtors_aux08049f1c D _ d So_handle w _ gmon_start _ 08048c3a T _ i686.get _ mongod _ mongot _ libc_csu_init U _ libc_start_main @ GLIBC_2.0 U __ stack_chk_fail @ resolve A _ edata08049f2c A _ end08048c68 T _ comment R _ comment T _ init08048800 T _ start08049f28 B comment W data_start U exit @ GLIBC_2.0 U fprintf @ Brief t handle T main U mysql_close U comment U mysql_error U comment U mysql_free_result U mysql_init U comment U mysql_real_connect U comment t comment d p.5788 U printf @ GLIBC_2.0 U putchar @ GLIBC_2.0 U puts @ GLIBC_2.008049f24 B stderr @ GLIBC_2.0wzb @ wzb-desktop: ~ /Test $

Wzb @ wzb-desktop :~ /Test $ mysql_configCopyright 2009 Sun Microsystems, Inc. this software comes with absolutely no warranty. this is free software, and you are welcome to modify and redistribute it under the GPL licenseGet compiler flags for using the MySQL client library. usage: mysql_config [OPTIONS] -- cflags [-I/usr/local/include]-?, -- Help Display this help and exit. -- include [-I/usr/local/include] -- libs [-L/usr/local/lib-lmysql-lpthread] -- libs_r [-L/usr/local/lib- lmysql-lpthread] -- version [6.0.2] wzb @ wzb-desktop: ~ /Test $ mysql_config -- libs-L/usr/local/lib-lmysql-lpthreadwzb @ wzb-desktop :~ /Test $ mysql_config -- libs_r-L/usr/local/lib-lmysql-lpthreadwzb @ wzb-desktop :~ /Test $ mysql_config -- include-I/usr/local/includewzb @ wzb-desktop :~ /Test $

Link below: http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html

Howto: Connect MySQL server using C program API under Linux or UNIX

By Vivek Gite on May 31,200 7· 56 comments

From my mailbag:

How do I write a C program to connect MySQL database server?

MySQL database does support C program API just like PHP or perl.

The c api code is distributed with MySQL. It is stored in the mysqlclient library and allows C programs to access a database.

Parameters of the clients in the MySQL source distribution are written in C. if you are looking for examples that demonstrate how to use the c api, take a look at these clients. you can find these in the clients directory in the MySQL source distribution.

Requirements

Make sure you have development environment installed such as gcc, mysql development package etc. Following is the list summarize the list of packages to compile program:

  • 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
Sample C Program

Following instructions shocould work on any Linux distro or UNIX computer. Here is the small program that connects to mysql server and list tables from mysql database. (download link ):

* Simple C program that connects to MySQL Database server */# include <mysql. h> # include <stdio. h> 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 );}

How do I compile and link program against MySQL libs?

MySQL comes with a special script called mysql_config. It provides you with useful information for compiling your MySQL client and connecting it to MySQL database server. You need to use following two options.
Pass-- LibsOption-Libraries and options required to link with the MySQL client library.

$ mysql_config --libs
Output:

-L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto

Pass-- CflagsOption-Compiler flags to find include files and critical compiler flags and defines used when compiling the libmysqlclient library.
$ 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 pass abve option to gnu c compiler I. e. gcc. So to compile abve program, enter:
$ gcc -o output-file $(mysql_config --cflags)mysql-c-api.c $(mysql_config --libs)
Now execute program:
$ ./output-file
Output:

MySQL Tables in mysql database:columns_privdbfunchelp_categoryhelp_keywordhelp_relationhelp_topichosttables_privtime_zonetime_zone_leap_secondtime_zone_nametime_zone_transitiontime_zone_transition_typeuser 
References:
  • MySQL c api-A must read-official MySQL c api documentation

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.