To access the mysql database, c ++ first put the include in the mysql directory under the project directory, and then put libmysql. lib and libmysql. dll under the debug directory.
# Include # Include Otherwise, a compilation error occurs.
# Include "stdafx. h"
# Include
# Include "include/mysql. h"
# Include
Using namespace std;
# Pragma comment (lib, "libmysql. lib ")
Int _ tmain (int argc, _ TCHAR * argv [])
{
MYSQL mysql;
MYSQL_RES * result = NULL;
MYSQL_FIELD * fd;
MYSQL_ROW SQL _row;
Int res;
Mysql_init (& mysql );
If (! Mysql_real_connect (& mysql, "172.1.1.1", "root", "123456", "mysql", 3306, 0, 0 ))
{
Fprintf (stderr, "Failedtoconnecttodatabase: Error: % s // n", mysql_error (& mysql ));
} Else {
Mysql_query (& mysql, "set names gbk"); // sets the encoding format. Otherwise, Chinese characters cannot be displayed in cmd.
Res = mysql_query (& mysql, "select * from help_category"); // if the value is not 0, an error occurs.
If (! Res ){
Result = mysql_store_result (& mysql );
If (result ){
Int I = 0, j;
Cout <"number of result:" <(unsigned long) mysql_num_rows (result) <
J = mysql_num_fields (result); // Obtain the number of columns
For (I = 0; I {
Fd = mysql_fetch_field (result); // Obtain the column name
Cout < Name <"/t ";
}
Cout < While (SQL _row = mysql_fetch_row (result) {// Obtain data in each row
For (I = 0; I {
If (NULL! = SQL _row [I]) // prevents data from being empty
Cout < }
Cout < }
}
} Else {
Cout <"query SQL failed! "< }
}
If (result! = NULL ){
Mysql_free_result (result); // release the result resource
}
Mysql_close (& mysql); // disconnect
System ("pause ");
Return 0;
}