First make sure that you have a MySQL-installed development package
Under Ubuntu do the following command installation, other distributions please check it yourself
Install Libmysqlclient-dev
The sample code is as follows:
#include <iostream>#include<cstdio>#include<cstdlib>#include<mysql.h>using namespacestd;intMain () {MYSQL*conn =Mysql_init (NULL); Conn= Mysql_real_connect (conn,"localhost","Root","Lyy","Test",0Null0); if(!conn) {Perror ("Mysql_real_connect"); Exit (1); } intres = mysql_query (conn,"select * FROM teacher"); if(res) {printf ("mysql_query:%s\n", MYSQL_ERROR (conn)); Exit (1); } Else{mysql_res*result =Mysql_store_result (conn); if(Result) { for(inti =0; I < mysql_num_rows (result); i++) {Mysql_row ROW=mysql_fetch_row (Result); for(intj =0; J < Mysql_num_fields (result); J + +) {printf ("%s\t", Row[j]); } printf ("\ n"); }} mysql_free_result (Result); } Res= mysql_query (conn,"Delete from teacher where id = 2"); if(res) {printf ("mysql_query:%s\n", MYSQL_ERROR (conn)); Exit (1); } Res= mysql_query (conn,"INSERT INTO teacher values (2, ' Lucy ', 12345678, ' F ')"); if(res) {printf ("mysql_query:%s\n", MYSQL_ERROR (conn)); Exit (1); } mysql_close (conn); return 0;}
Execute the following command to compile
g++-O test $ (mysql_config--cflags) mysql_test. CPP $ (mysql_config--libs)
Description
There is a special script in MySQL called Mysql_config. It will compile the MySQL client for you and connect to the MySQL server to provide useful information. You need to use the following two options.
1.--libs option-the libraries and options required to connect to the MySQL client library.
$ mysql_config--libs
2.--cflags option-Use the necessary Include files option, and so on.
$ mysql_config--cflags
Linux/C + + connection MySQL