C++ operates MYSQL database

1. Install mysql

slightly

2. Create a C++ console program and create a new CPP source file, such as: sqlconn.cpp

3. Add MySQL\MySQL\MySQL Server 5.7\include in the mysql installation directory to the properties->c/C++->general->additional include directory in the project project

  4. Add library directory

 5. Add dependency "libmysql.lib"

 

6. Change the operating platform to X64 (this step is very important, otherwise an error will be reported when compiling)

7. Add the header file to the source file:

#include <winsock.h> //Pay attention to the order, it should be placed before mysql.h
#include <mysql.h>//In the console project, include <winsock.h> before mysql.h

8. Write your own database operation program

Example:

void test1()
{
 MYSQL *pConn;
 pConn = mysql_init(NULL);
 //The meaning of the 2nd, 3rd, 4th, and 5th parameters are: server address, user name, password, database name, and the sixth is the mysql port number (0 is the default value of 3306)
 if(!mysql_real_connect(pConn,"localhost","root","root","test",0,NULL,0))
 {  
  printf("Unable to connect to database: %s",mysql_error (pConn));
  return;
 }
 mysql_query(pConn,"set names gbk");//Prevent garbled characters. If the setting is consistent with the encoding of the database, there will be no garbled
 characters//SET NAMES x is equivalent to SET character_set_client = x;SET character_set_results = x;SET character_set_connection = x;
 //write set character set gbk; the query will not be garbled, but the parameterized insertion will report an error. And set names gbk will not be garbled


 //mysql_real_query has one more parameter than mysql_query: the length of the string query, so it is suitable for query with binary data, and the string query of mysql_query cannot contain binary, because it ends with \0
 //mysql_query() cannot pass binary BLOB field, because \0 in binary information will be misjudged as the end of the statement. mysql_real_query() can.
 if(mysql_query(pConn,"select * from persons"))
 {
  printf("Query failed: %s",mysql_error(pConn));
  return;
 }

 //mysql_store_result is an offline data set that retrieves the query results to the client at one time, and consumes memory when the results are large.
 //mysql_use_result puts the query result on the server, and the client reads it line by line through the pointer, saving client memory. But a MYSQL* connection can only have one unclosed mysql_use_result query at the same time
 MYSQL_RES *result = mysql_store_result(pConn);
 MYSQL_ROW row;
 while(row = mysql_fetch_row(result))
 {
  printf("%s %s\n",row[ 1],row[2]);
 }

 mysql_free_result(result);
 mysql_close(pConn);
}

9.将mysq目录….. \MySQL\MySQL Server 5.7\lib 下的libmysql.dll放到生成的exe目录下,编译执行即可。

 

参考:

1.http://www.cnblogs.com/rupeng/archive/2012/10/06/2712841.html

2.http://bbs.csdn.net/topics/390523114

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325773869&siteId=291194637