C ++ access the mysql database

Source: Internet
Author: User
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;
}

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.