In Linux, it took me a long time to figure out how to process the MySQL database sample program in C language.
Compile:
Reference
G ++-Imysql/include-Lmysql/lib-o a. out a. cpp-lmysqlclient-lz
This mysql directory is the source code directory of a mysql. If mysql-devel is installed in/usr/ooxx/mysql, you can go down the source code by yourself.
# Include <iostream>
# Include <string>
# Include <fstream>
# Include "mysql. h"
Using namespace std;
MYSQL * conn = NULL; // MySQL connection handle
// Read Configuration
Bool read_conf (string & dbhost,
String & dbuser,
String & dbpass,
String & dbname ){
Ifstream is ("judge. conf ");
Is> dbhost> dbuser> dbpass> dbname;
Return true;
}
Bool query (){
Int status, state, state2;
MYSQL_RES * res;
MYSQL_ROW row;
String cmd;
MYSQL * conn, mysql;
String dbhost, dbuser, dbpass, dbname;
If (read_conf (dbhost, dbuser, dbpass, dbname) {// read the database
If (mysql_init (& mysql) = NULL ){
Fprintf (stderr, "initialization error \ n ");
Return false;
}
Conn = mysql_real_connect (& mysql, dbhost. c_str (), dbuser. c_str (),
Dbpass. c_str (), dbname. c_str (), NULL,
"/Var/run/mysqld. sock", 0 );
If (conn = NULL) {// connection failed
Fprintf (stderr, "connection failed! \ N ");
Return false;
}
} Else {// reading configuration failed
Fprintf (stderr, "reading configuration failed! \ N ");
Return false;
}
Cmd = "select ooxx from ooxx ";
Cout <"Command:" <cmd <endl;
State = mysql_query (conn, cmd. c_str ());
Cout <"state:" <state <endl;
If (state! = 0) {// query Error
Fprintf (stderr, "% s \ n", mysql_error (conn ));
Return false;
}
Res = mysql_store_result (conn );
Cout <"affected_rows:" <conn-> affected_rows <endl;
While (row = mysql_fetch_row (res), row! = NULL ){
Printf ("% s \ n", row [0]);
}
Return true;
}
Int main (){
Query ();
Return 0;
}
If you think this article is useful to you, leave a message below to let me know. Thank you very much ^_^
Reprint please indicate from http://felix021.com/blog/read.php? 1505 (if it is reproduced, the original source is indicated), thank you :)