VS2013 operates the database through MySQL ConnectorC++

Recently, I need to connect and operate the mysql database in the project, so I studied the method of C++ connecting to the mysql database.

There are many ways to connect to mysql database in C++, 1) connect using mysql API; 2) connect through ADO; 3) connect through MySQL Connector/C++ officially provided by MySQL.

The editor uses the C++ programming environment, and found MySQL Connector/C++ in the Connectors provided by the MySQL official website (I think the official website should be more reliable). So I chose MySQL Connector/C++ to connect to the database.

 MySQL Connector/C++ is a MySQL connector developed by Sun Microsystems. It provides OO-based programming interface and database driver to operate MySQL server. Unlike many other existing C++ interface implementations, Connector/C++ follows the JDBC specification. In other words, the API of Connector/C++ Driver is mainly based on the JDBC interface of Java language. JDBC is a standard industrial interface for connecting java language with various databases. Connector/C++ implements most of the JDBC4.0 specifications. If the developers of C++ programs are familiar with JDBC programming, they will get started soon.

OK, before the official lecture, the editor assumes that everyone's MySQL service has been installed and running and can be accessed from the client, let's enter the topic~

1. Download MySQL Connector/C++

Go to MySQL official website to download MySQL connector/C++, download address https://dev.mysql.com/downloads/connector/cpp/

You can download the zip version, which is the free installation version (recommended). You can also download the msi version, which is the installation version. You can also download the source code and compile it yourself.

Download the corresponding version according to your system platform. According to the official recommendation: It is best to use the same vs version as the compiled MySQLConnector for development and use, otherwise there may be many unexpected problems. (This editor made an attempt and listed unexpected problems at the end of the article (─━ _ ─━✧))

The VS version used by the editor is 2013. According to the official instructions (below), the downloaded version of MySQLConnector is 1.1.9, which is free of installation.

After the download is complete, unzip it and you can see two folders including include and lib in the directory.

include\ is the header file;

lib\ contains DLL version (dynamic) library and LIB version (static) library.

  • mysqlcppconn.dll and mysqlcppconn.lib are files of dynamic libraries;
  • mysqlcppconn-static.lib is a static library.

   

2. Prepare the boost library

Since the interface of the boost library is used in the Connector/C++ library, we need to include the boost library directory in our application.

You can download boost at https://www.boost.org/users/download/ , or download from SourceForge: https://sourceforge.net/projects/boost/files/boost/

You can also download the source code and compile it yourself. The specific process is not described in detail here. . . ( ̄^ ̄゜) (Children's shoes can read this post: https://blog.csdn.net/lt4959/article/details/108974041 )

......

......

The editor compiled the boost-1.58 library.

 

3. Use Connector/C++ to operate database connection

Create a new console project TestMySQL in VS, then set the included files and libraries in the project (as shown in the figure below), the 32bit version used here, children's shoes, please configure according to your needs.

Add the boost library directory and the ConnectorC++ library directory to the additional include directory. (PS. The editor has configured the boost library directory as an environment variable, so it can be configured directly through the environment variable name. = ̄ω ̄=)

Add the ConnectorC++ library directory to the additional library directory

Additional dependencies add ConnectorC++ library,

  • Use static library, add mysqlcppconn-static.lib to dependencies

  • Use the dynamic library, add mysqlcppconn.lib to the dependencies, and copy mysqlcppconn.dll to the output path of the TestMySQL project

Note: If you use a static library, you also need to define the macro CPPCONN_LIB_BUILD , otherwise the header file will import functions in the same way as a dynamic library, resulting in a bunch of errors (see question 2 )

You can define the macro CPPCONN_LIB_BUILD before including the header file, or add it in the preprocessor definition.

 

4. Write test code

(PS. Editor has created a new database named "my_test" in the database)


#include "stdafx.h"

/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include <jdbc/mysql_connection.h>

#include <jdbc/cppconn/driver.h>
#include <jdbc/cppconn/exception.h>
#include <jdbc/cppconn/resultset.h>
#include <jdbc/cppconn/statement.h>

#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	try {
		sql::Driver *driver;
		sql::Connection *con;
		sql::Statement *stmt;
		sql::ResultSet *res;

		/* Create a connection */
		driver = get_driver_instance();
		con = driver->connect("tcp://127.0.0.1:3306", "root", "ahdms520");
		if (con == NULL)
		{
			cout << "conn is null" << endl;
			goto END;
		}
		cout << "连接数据库服务器成功" << endl;

		/* Connect to the MySQL test database */
		con->setSchema("my_test");

		stmt = con->createStatement();
		if (stmt == NULL)
		{
			cout << "stmt is null" << endl;
			goto END;
		}

		res = stmt->executeQuery("SELECT * FROM `user`;");
		int i = 0;
		while (res->next()) {
			// You can use either numeric offsets...
			cout << "id = " << res->getInt(1); // getInt(1) returns the first column
			// ... or column names for accessing results.
			// The latter is recommended.
			cout << ", name = '" << res->getString("name").c_str() << "'" << endl;
			i++;
		}
		cout << "共" << i << "条" << endl;

		con->close();
		delete res;
		delete stmt;
		delete con;
	}
	catch (sql::SQLException& e) 
	{
		std::cout << "# ERR: " << e.what();
		std::cout << " (MySQL error code: " << e.getErrorCode();
		std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;
	}
END:
	system("pause");

	return 0;
}

Compile and run results:

(๑╹ヮ╹๑)ノ Studying makes me happy

 

/********************************** Gorgeous dividing line ლ(❛◡❛✿)ლ**** **********************************/

Here is a list of the pits that the editor has waded through during the research process~

Question one

The Zip package downloaded from the MySQL official website only has the release repository. If you use its LIB (static) library in the debug mode of VS , a bunch of errors will be reported as follows,

错误 1 error LNK2038: 检测到“_ITERATOR_DEBUG_LEVEL”的不匹配项: 值“0”不匹配值“2”(TestMySQL.obj 中) E:\workspace\MyTest\TestMySQL\TestMySQL\mysqlcppconn-static.lib(mysql_driver.obj) TestMySQL

This means that the current project is the Debug version, and the referenced library file is the Release version, which leads to a mismatch. So change the current Debug mode to Release mode .

Reference: https://www.cnblogs.com/lisuyun/p/6410393.html

Children's shoes can rest assured that using DLL (dynamic) library will not have this problem . O(∩_∩)O

 

Question two

If you use a static library, the compiler will report the following error. Then it should be that the CPPCONN_LIB_BUILD macro is not defined, and the program imports the function in the way of a dynamic library.

错误 14 error LNK1120: 6 个无法解析的外部命令 E:\workspace\MyTest\TestMySQL\Release\TestMySQL.exe TestMySQL

错误 8 error LNK2001: 无法解析的外部符号 "__declspec(dllimport) class sql::mysql::MySQL_Driver * __cdecl sql::mysql::get_driver_instance(void)" (__imp_?get_driver_instance@mysql@sql@@YAPAVMySQL_Driver@12@XZ) E:\workspace\MyTest\TestMySQL\TestMySQL\TestMySQL.obj TestMySQL

错误 13 error LNK2001: 无法解析的外部符号 "__declspec(dllimport) public: __thiscall sql::SQLString::~SQLString(void)" (__imp_??1SQLString@sql@@QAE@XZ) E:\workspace\MyTest\TestMySQL\TestMySQL\TestMySQL.obj TestMySQL

错误 12 error LNK2001: 无法解析的外部符号 "__declspec(dllimport) public: __thiscall sql::SQLString::SQLString(char const * const)" (__imp_??0SQLString@sql@@QAE@QBD@Z) E:\workspace\MyTest\TestMySQL\TestMySQL\TestMySQL.obj TestMySQL

错误 11 error LNK2001: 无法解析的外部符号 "__declspec(dllimport) public: char const * __thiscall sql::SQLString::c_str(void)const " (__imp_?c_str@SQLString@sql@@QBEPBDXZ) E:\workspace\MyTest\TestMySQL\TestMySQL\TestMySQL.obj TestMySQL

错误 10 error LNK2001: 无法解析的外部符号 "__declspec(dllimport) public: class std::basic_string,class std::allocator > const & __thiscall sql::SQLException::getSQLState(void)const " (__imp_?getSQLState@SQLException@sql@@QBEABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) E:\workspace\MyTest\TestMySQL\TestMySQL\TestMySQL.obj TestMySQL

错误 9 error LNK2001: 无法解析的外部符号 "__declspec(dllimport) public: int __thiscall sql::SQLException::getErrorCode(void)const " (__imp_?getErrorCode@SQLException@sql@@QBEHXZ) E:\workspace\MyTest\TestMySQL\TestMySQL\TestMySQL.obj TestMySQL

Solution : Add the CPPCONN_LIB_BUILD macro definition in the preprocessor definition.

Reference: https://www.cnblogs.com/sankeyou/p/4054472.html

 

Question three

When the value of the varchar field is obtained through getString after executing the query statement , it will crash due to a memory exception .

Solution : Get the varchar field value in the following way,

res->getString("Column name").c_str();

Reference: https://stackoverflow.com/questions/4822958/mysql-c-connector-getstring-doesnt-work-correctly-while-getint-works-perfe

 

Question four

If MySQL Connector/C++ 8.0.21 is used in VS2013 (that is, the version compiled by vs2019 is used) static library,

After compiling, it prompts a bunch of errors as follows ฺ(▼ヘ▼#)

Sorry, this pit editor can't get out. It is recommended that children's shoes use the appropriate version. ㄟ( ▔, ▔ )ㄏ  

(PS. Friends who know this problem are welcome to tell the editor (^_-))

Guess you like

Origin blog.csdn.net/lt4959/article/details/109055284