<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>MySQL C++ Connector &#8211; 编码无悔 /  Intent &amp; Focused</title>
	<atom:link href="https://www.codelast.com/tag/mysql-c-connector/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codelast.com</link>
	<description>最优化之路</description>
	<lastBuildDate>Sun, 03 May 2020 12:21:13 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>[原创]VC++连接/操作MySQL数据库(通过MySQL C API)</title>
		<link>https://www.codelast.com/%e5%8e%9f%e5%88%9bvc%e8%bf%9e%e6%8e%a5%e6%93%8d%e4%bd%9cmysql%e6%95%b0%e6%8d%ae%e5%ba%93%e9%80%9a%e8%bf%87mysql-c-api/</link>
					<comments>https://www.codelast.com/%e5%8e%9f%e5%88%9bvc%e8%bf%9e%e6%8e%a5%e6%93%8d%e4%bd%9cmysql%e6%95%b0%e6%8d%ae%e5%ba%93%e9%80%9a%e8%bf%87mysql-c-api/#respond</comments>
		
		<dc:creator><![CDATA[learnhard]]></dc:creator>
		<pubDate>Sat, 04 May 2013 16:58:05 +0000</pubDate>
				<category><![CDATA[Windows]]></category>
		<category><![CDATA[原创]]></category>
		<category><![CDATA[ADO]]></category>
		<category><![CDATA[C++连接MySQL]]></category>
		<category><![CDATA[MySQL C API]]></category>
		<category><![CDATA[MySQL C++ Connector]]></category>
		<category><![CDATA[VC连接MySQL]]></category>
		<guid isPermaLink="false">http://www.codelast.com/?p=5904</guid>

					<description><![CDATA[<p>
这是一篇非常基础的文章。想必每个刚开始学写程序的人，都很有可能会遇到这样的问题：如何用Visual C++编写一个可以操作（读写数据）MySQL的程序？<br />
由于一直在Linux下工作，我很久没写Windows程序了，但是最近急于写一个操作MySQL的Windows程序来用，于是又重新拿起了VC++，写了一个MFC应用程序，临阵磨枪，不亮也光嘛。<br />
在写这个程序的过程中，遇到的有些问题觉得挺扯蛋的，于是干脆就把整个过程给记下来了，整理成这篇文章，知识共享。<br />
开发环境：Visual Studio 2005，Win 7 32位<br />
<span id="more-5904"></span><br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
<span style="background-color:#00ff00;">【1】</span>在开发VC++程序时，怎样访问MySQL<br />
方法很多，我只就我了解过的来说一说。<br />
<span style="background-color:#ee82ee;">①</span>ADO<br />
为了开发方便，你可以通过ADO来连接MySQL，这也是很多教程提到的方法，写起程序来确实简单，但它有一个问题：你需要先安装MySQL ODBC Driver，并在OS里配置一个数据源，否则程序写好了也是不能连接MySQL的。因此，你在一台计算机上配置好了之后，把你写的程序拷贝到另一台计算机上，又要在OS里重新安装MySQL ODBC Driver并配置数据源，这得有多蛋疼啊？！我觉得这是减轻了编码的工作，却增加了部署的工作，因此，不考虑这种方法，放弃ADO。<br />
<!--more--><br />
不过，这里还是要提一下用ADO访问MySQL的代码有多么简单:<br />
在你的VC++项目中初始化ADO（例如在stdafx.h中）：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
#import &#34;msado15.dll&#34; no_namespace rename(&#34;EOF&#34;,&#34;adoEOF&#34;)
</pre>
<p>其中，msado15.dll是在Windows系统盘里的一个文件，你可以搜索到。可以把它拷贝到工程项目下，就无需写完整路径了。<br />
然后，在操作数据库之前（一般是在项目的App类中），还要初始化一次：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
if (!AfxOleInit()) {
    AfxMessageBox(&#34;初始化失败！&#34;);
    return FALSE;
}
</pre>
<p>无需其他特殊的设置，接着就可以开始写访问MySQL的程序了，关于读写MySQL的示例代码，这里就不附上了。<br />
没错，就这么简单，你无需在项目中链接到任何MySQL的lib，也无需去找MySQL相关的头文件。ADO确实很适合想要在代码编写上省事的人。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
而下面所说的几种方法都是在开发阶段麻烦，但在部署阶段简单（拷贝相关文件到目标机器上即可用，无需配置数据源）。所以，你可以根据实际情况做出取舍。<br />
<span style="background-color:#dda0dd;">②</span>使用MySQL C API<br />
<a href="http://dev.mysql.com/doc/refman/5.0/en/c-api.html" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">MySQL C API</span></a>是什么？官方说明如下：</p>
<blockquote>
<p>
		The C API provides low-level access to the MySQL client/server protocol and enables C programs to access database contents.</p></blockquote>&#8230; <a href="https://www.codelast.com/%e5%8e%9f%e5%88%9bvc%e8%bf%9e%e6%8e%a5%e6%93%8d%e4%bd%9cmysql%e6%95%b0%e6%8d%ae%e5%ba%93%e9%80%9a%e8%bf%87mysql-c-api/" class="read-more">Read More </a>]]></description>
										<content:encoded><![CDATA[<p>
这是一篇非常基础的文章。想必每个刚开始学写程序的人，都很有可能会遇到这样的问题：如何用Visual C++编写一个可以操作（读写数据）MySQL的程序？<br />
由于一直在Linux下工作，我很久没写Windows程序了，但是最近急于写一个操作MySQL的Windows程序来用，于是又重新拿起了VC++，写了一个MFC应用程序，临阵磨枪，不亮也光嘛。<br />
在写这个程序的过程中，遇到的有些问题觉得挺扯蛋的，于是干脆就把整个过程给记下来了，整理成这篇文章，知识共享。<br />
开发环境：Visual Studio 2005，Win 7 32位<br />
<span id="more-5904"></span><br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
<span style="background-color:#00ff00;">【1】</span>在开发VC++程序时，怎样访问MySQL<br />
方法很多，我只就我了解过的来说一说。<br />
<span style="background-color:#ee82ee;">①</span>ADO<br />
为了开发方便，你可以通过ADO来连接MySQL，这也是很多教程提到的方法，写起程序来确实简单，但它有一个问题：你需要先安装MySQL ODBC Driver，并在OS里配置一个数据源，否则程序写好了也是不能连接MySQL的。因此，你在一台计算机上配置好了之后，把你写的程序拷贝到另一台计算机上，又要在OS里重新安装MySQL ODBC Driver并配置数据源，这得有多蛋疼啊？！我觉得这是减轻了编码的工作，却增加了部署的工作，因此，不考虑这种方法，放弃ADO。<br />
<!--more--><br />
不过，这里还是要提一下用ADO访问MySQL的代码有多么简单:<br />
在你的VC++项目中初始化ADO（例如在stdafx.h中）：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
#import &quot;msado15.dll&quot; no_namespace rename(&quot;EOF&quot;,&quot;adoEOF&quot;)
</pre>
<p>其中，msado15.dll是在Windows系统盘里的一个文件，你可以搜索到。可以把它拷贝到工程项目下，就无需写完整路径了。<br />
然后，在操作数据库之前（一般是在项目的App类中），还要初始化一次：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
if (!AfxOleInit()) {
    AfxMessageBox(&quot;初始化失败！&quot;);
    return FALSE;
}
</pre>
<p>无需其他特殊的设置，接着就可以开始写访问MySQL的程序了，关于读写MySQL的示例代码，这里就不附上了。<br />
没错，就这么简单，你无需在项目中链接到任何MySQL的lib，也无需去找MySQL相关的头文件。ADO确实很适合想要在代码编写上省事的人。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
而下面所说的几种方法都是在开发阶段麻烦，但在部署阶段简单（拷贝相关文件到目标机器上即可用，无需配置数据源）。所以，你可以根据实际情况做出取舍。<br />
<span style="background-color:#dda0dd;">②</span>使用MySQL C API<br />
<a href="http://dev.mysql.com/doc/refman/5.0/en/c-api.html" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">MySQL C API</span></a>是什么？官方说明如下：</p>
<blockquote>
<p>
		The C API provides low-level access to the MySQL client/server protocol and enables C programs to access database contents.</p>
</blockquote>
<p>你可以通过它来访问MySQL。我最终用的就是这种方法。<br />
<span style="background-color:#dda0dd;">③</span>使用MySQL C++ Connector<br />
<a href="http://dev.mysql.com/doc/refman/5.6/en/connector-cpp.html" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">MySQL C++ Connector</span></a>是什么？官方说明如下：</p>
<blockquote>
<p>
		MySQL Connector/C++ is a MySQL database connector for C++. It lets you develop C++ applications that connect to the MySQL Server.</p>
</blockquote>
<p>那么，它与MySQL的C API有什么区别呢？为什么要使用它？官方说明如下：</p>
<blockquote>
<div>
		MySQL Connector/C++ offers the following benefits for C++ users compared to the MySQL C API (MySQL client library):</div>
<div>
		Convenience of pure C++; no C function calls required</div>
<div>
		Supports JDBC 4.0, an industry standard API</div>
<div>
		Supports the object-oriented programming paradigm</div>
<div>
		Reduces development time</div>
<div>
		Licensed under the GPL with the FLOSS License Exception</div>
<div>
		Available under a commercial license upon request</div>
</blockquote>
<div>
	可见其优点多多。但有一点要注意：如果使用MySQL C++ Connector，在开发阶段比MySQL C API要做更多的工作（下载、配置各种依赖库，等等），如果你想稍微简单一点，就使用MySQL C API；如果你不嫌麻烦，就使用MySQL C++ Connector，它的优点正如上面所说，这里就不复述了。<br />
	MySQL C++ Connector的下载链接在<a href="http://dev.mysql.com/downloads/connector/cpp/" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">这里</span></a>。你可以根据你的平台下载相应的版本，例如&ldquo;<span style="color:#0000ff;">Windows (x86, 32-bit), ZIP Archive</span>&rdquo;，解压出来会看到 include 和 lib 这两个目录，里面的文件都是我们需要的。</div>
<p>你可以参考MySQL官方的<a href="http://dev.mysql.com/doc/refman/5.6/en/connector-cpp-apps-windows-visual-studio.html" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">这篇文章</span></a>。它比较详细地描述了如何创建一个VC++工程并使用MySQL C++ Connector的方法。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
这里不得不提醒你的是，前面已经说了，比起使用MySQL C API，用MySQL C++ Connector来开发程序要做更多的工作，体现在：MySQL C++ Connector依赖于MySQL库、<a href="http://www.boost.org/" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">Boost</span></a>，因此你还要先有MySQL的开发包、Boost库。Boost是个麻烦的东西，因为它很大，编译出lib很耗时间，很耗CPU资源，如果你和我一样，用的是一台老爷机，那么你会感觉到编译出Boost lib的过程异常痛苦。另外，在撮合了MySQL C++ Connector、Boost、MySQL的一个项目中，如果你的项目参数设置不对，会出现各种奇怪的问题，下面我列举一二：<br />
<span style="background-color: rgb(221, 160, 221);">㈠</span><span style="color: rgb(178, 34, 34);">LINK : warning LNK4098: 默认库&ldquo;MSVCRT&rdquo;与其他库的使用冲突；请使用 /NODEFAULTLIB:library</span><br />
解决办法是修改VC++项目属性：<br />
<span style="color: rgb(0, 0, 255);">项目&rarr;编辑项目属性&rarr;链接器&rarr;输入&rarr;&ldquo;忽略特定库&rdquo;里填上&ldquo;MSVCRT.lib&rdquo;（不含引号）</span>。</p>
<p><span style="background-color: rgb(221, 160, 221);">㈡</span><span style="color: rgb(178, 34, 34);">msvcprt.lib(MSVCP80.dll) : error LNK2005: &quot;public: __thiscall std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt;::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt;(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;)&quot; (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z) 已经在 XXX.obj 中定义</span><br />
解决办法是修改VC++项目属性：<br />
<span style="color: rgb(0, 0, 255);">项目&rarr;编辑项目属性&rarr;C/C++&rarr;代码生成&rarr;运行时库&rarr;修改为&ldquo;</span><span style="color: rgb(0, 128, 0);">多线程调试 DLL (/MDd)</span><span style="color: rgb(0, 0, 255);">&rdquo;或&ldquo;</span><span style="color: rgb(0, 128, 0);">多线程 DLL (/MD)</span><span style="color: rgb(0, 0, 255);">&rdquo;</span><br />
同时，因为此项修改，可能会导致另一个编译错误：<br />
<span style="color: rgb(178, 34, 34);">fatal error C1189: #error : &nbsp;Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]</span><br />
如果看到这个错误提示，那么就要再次修改项目属性：<br />
<span style="color: rgb(0, 0, 255);">项目&rarr;编辑项目属性&rarr;配置属性&rarr;常规&rarr;MFC的使用&rarr;修改为&ldquo;</span><span style="color: rgb(0, 128, 0);">在共享 DLL 中使用 MFC</span><span style="color: rgb(0, 0, 255);">&rdquo;</span><br />
然后就解决了此问题。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
这可能只是各种编译问题中的一小部分，除非你运气好，没遇到这些问题，或者你愿意花很多时间来搞定它，否则你一定不想在时间紧张的时候看到这些烦人的错误。</p>
<p><span style="background-color:#00ff00;">【2】</span>头文件，lib的目录结构<br />
综上所述，我使用的是MySQL C API，那么我需要拿到相关的头文件和lib文件。我是先下载到&nbsp;mysql-installer-community-5.6.11.0.msi 这个MySQL的安装包，然后（无需安装）用<a href="http://legroom.net/software/uniextract" target="_blank" rel="noopener noreferrer"><span style="background-color:#ffa07a;">Universal Extractor</span></a>把它解压出来，得到&nbsp;mysql-5.6.11-win32.msi 文件，再次使用Universal Extractor解压，最终会拿到include和lib两个目录，就是我们所需要的。然后就把它们都放到项目目录下，我是像下面这样组织目录结构的：</p>
<pre class="brush:plain;first-line:1;pad-line-numbers:true;highlight:、;collapse:false;">
├─include
│  └─mysql
│      └─server
│          │  big_endian.h
│          │  (后面省略)
│          └─mysql
│              │  client_authentication.h
│              │  (后面省略)
│              └─psi
│                      mysql_file.h
│                      (后面省略)
│                      
├─lib
│  └─mysql
│      └─server
│          │  libmysql.dll
│          │  libmysql.lib
│          │  mysqlclient.lib
│          │  
│          ├─debug
│          │      mysqlclient.lib
│          │      
│          └─plugin
│                  adt_null.dll
│                  auth.dll
│                  auth_test_plugin.dll
│                  libdaemon_example.dll
│                  mypluglib.dll
│                  qa_auth_client.dll
│                  qa_auth_interface.dll
│                  qa_auth_server.dll
│                  semisync_master.dll
│                  semisync_slave.dll
│                  validate_password.dll
</pre>
<p>其中，include下的是头文件，lib下的是库文件，它们下面的boost、connector、server分别是Boost、MySQL C++ Connector、MySQL的文件。<br />
有了这样的目录结构，VC++项目怎么设置？<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
<span style="background-color:#00ff00;">【3】</span>Visual C++项目设置<br />
打开项目属性设置对话框，依次设置如下（无论是对Debug，还是Release，都这样设置）：<br />
<span style="background-color:#dda0dd;">①</span>&ldquo;配置属性&rdquo;&rarr;&ldquo;常规&rdquo;&rarr;&ldquo;MFC的使用&rdquo;&rarr;&ldquo;在静态库中使用MFC&rdquo;（这一项不一定非要这样设置）。<br />
<span style="background-color:#dda0dd;">②</span>&ldquo;配置属性&rdquo;&rarr;&ldquo;C/C++&rdquo;&rarr;&ldquo;常规&rdquo;&rarr;&ldquo;附加包含目录&rdquo;，把上面提到的include目录添加进去。对应到上面所说的层级结构，它应该是 <span style="color:#0000ff;">XXX\include\mysql\server</span> 这样的目录。如下图所示(后面的步骤也类似，不再图示)：</p>
<div style="text-align: center;">
	<img decoding="async" alt="VC++ project properties" src="http://www.codelast.com/wp-content/uploads/2013/05/project_properties.png" style="width: 243px; height: 200px;" /><br />
	&nbsp;</div>
<div style="text-align: center;">
	<img decoding="async" alt="VC++ add include directory" src="http://www.codelast.com/wp-content/uploads/2013/05/add_include_directory.png" style="width: 558px; height: 232px;" /></div>
<p><span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
<span style="background-color:#dda0dd;">③</span>&ldquo;配置属性&rdquo;&rarr;&ldquo;链接器&rdquo;&rarr;&ldquo;常规&rdquo;&rarr;&ldquo;附加库目录&rdquo;，把上面提到的lib目录添加进去。对应到上面所说的层级结构，它应该是 <span style="color:#0000ff;">XXX\lib\mysql\server</span> 这样的目录。<br />
<span style="background-color:#dda0dd;">④</span>&ldquo;配置属性&rdquo;&rarr;&ldquo;链接器&rdquo;&rarr;&ldquo;输入&rdquo;&rarr;&ldquo;附加依赖项&rdquo;，填入&ldquo;<span style="color:#0000ff;">libmysql.lib</span>&rdquo;（不包含引号）。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
<span style="background-color: rgb(0, 255, 0);">【4】</span>程序编写<br />
我添加了一个类DataAccess，所有的数据库操作都通过这个类完成。这个类大概是长这个样子的（由于是截取下来的代码片段，所以如果有错误导致无法编译，还请见谅）：<br />
头文件：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
/**
 * DataAccess.h
 *
 * @author Darran Zhang @ codelast.com
 */

#pragma once

#include &quot;stdafx.h&quot;
#include &lt;string&gt;
#include &lt;winsock.h&gt;
#include &quot;mysql.h&quot;

class CDataAccess
{
public:
	CDataAccess(void);
	~CDataAccess(void);

private:
	MYSQL* m_pSQL;  
	MYSQL_RES* m_pSQLResultSet;

protected:
	BOOL m_bIsConnect;		// 数据库是否已连接

public:
	BOOL ConnectDB(const std::string &amp;strHost, const int nPort, const std::string &amp;strDBName, const std::string &amp;strUserName, const std::string &amp;strPassword);
	BOOL ExecuteQuery(std::string &amp;strSQL);
};
</pre>
<p>其中，如果没有包含 winsock.h 这个文件的话，编译时会报错：</p>
<blockquote>
<p>
		mysql_com.h(XXX) : error C2146: syntax error : missing &#39;;&#39; before identifier &#39;fd&#39;</p>
</blockquote>
<p>m_pSQL 和&nbsp;<span style="font-size: 14px;">m_pSQLResultSet 这两个指针的类型是在MySQL C API中定义的。</span><br />
ConnectDB()函数用于连接MySQL，ExecuteQuery()函数用于执行一句SQL。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
实现文件：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
/**
 * DataAccess.cpp
 *
 * @author Darran Zhang @ codelast.com
 */

#include &quot;DataAccess.h&quot;

using namespace std;

CDataAccess::CDataAccess(void)
{
  m_pSQL = NULL;
  m_pSQLResultSet = NULL;
  m_bIsConnect = FALSE;
}

CDataAccess::~CDataAccess(void)
{
  if(m_pSQL) {
    mysql_close(m_pSQL);
  }

  m_pSQL = NULL;
  m_pSQLResultSet = NULL;
}

BOOL CDataAccess::ConnectDB(const string &amp;strHost, const int nPort, const string &amp;strDBName, const string &amp;strUserName, const string &amp;strPassword)
{
  if (m_bIsConnect) {
    MessageBox(AfxGetMainWnd()-&gt;m_hWnd, _T(&quot;数据库已连接&quot;), _T(&quot;提示&quot;), MB_ICONWARNING | MB_OK);
    return TRUE;
  }

  mysql_library_init(0, NULL, NULL);  // 初始化MySQL C API库 
  if( (m_pSQL = mysql_init(NULL)) == NULL) {
    MessageBox(AfxGetMainWnd()-&gt;m_hWnd, _T(&quot;初始化MySQL连接失败&quot;), _T(&quot;错误&quot;), MB_ICONERROR | MB_OK);
    return FALSE;
  }
  mysql_options(m_pSQL, MYSQL_SET_CHARSET_NAME, &quot;gb2312&quot;);

  if (NULL == mysql_real_connect(m_pSQL, strHost.c_str(), strUserName.c_str(), strPassword.c_str(), strDBName.c_str(), nPort, NULL, 0)) {
      MessageBox(AfxGetMainWnd()-&gt;m_hWnd, _T(&quot;连接MySQL失败&quot;), _T(&quot;错误&quot;), MB_ICONERROR | MB_OK);
      return FALSE;
  }

  m_bIsConnect = TRUE;
  return m_bIsConnect;  // 返回连接是否成功的标志
}

BOOL CDataAccess::ExecuteQuery(string &amp;strSQL)
{
  if (!m_bIsConnect) {
    MessageBox(AfxGetMainWnd()-&gt;m_hWnd, _T(&quot;尚未连接MySQL&quot;), _T(&quot;错误&quot;), MB_ICONERROR | MB_OK);
    return FALSE;
  }

  size_t nReturnValue = mysql_real_query(m_pSQL, strSQL.c_str(), strSQL.length());
  return (0 == nReturnValue) ? TRUE : FALSE;
}
</pre>
<p>这个类的使用也很简单，构造一个DataAccess类对象来调用其方法即可。<br />
注意：有一句代码&nbsp;mysql_options(m_pSQL, MYSQL_SET_CHARSET_NAME, &quot;gb2312&quot;) 的作用是设置连接的字符集，我记得我测试的时候，使用gbk字符集的话，向数据库中插入的中文是乱码，所以在这里我将它设置为gb2312，经测试就没有问题了。<br />
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
上面的代码片段甚至于没有演示如何取出一个SQL查询得到的记录集，因此在这里补充一下。<br />
假设你有一张名为&ldquo;student&rdquo;的MySQL表，有两列：ID（主键），name（字符串）。现在要用程序取出该表里的所有记录，可以像下面那样做：</p>
<pre class="brush:cpp;first-line:1;pad-line-numbers:true;highlight:null;collapse:false;">
string strSQL = &quot;SELECT * FROM student&quot;;
if(mysql_query(m_pSQL, strSQL.c_str())) {
	MessageBox(AfxGetMainWnd()-&gt;m_hWnd, _T(&quot;查询数据库失败&quot;), _T(&quot;错误&quot;), MB_ICONERROR | MB_OK);
	return FALSE;
}

m_pSQLResultSet = mysql_store_result(m_pSQL);
MYSQL_ROW pSQLRow = NULL;

while (pSQLRow = mysql_fetch_row(m_pSQLResultSet)) {   // 循环读出每一行 
	for (int i = 0; i &lt;= 1; i++) { // 循环读出每一列 
		string strFieldValue = pSQLRow[i];
		if (0 == i) {	// 第1列 
			long nId = atol(strFieldValue.c_str());
		} else if (1 == i) {	// 第2列 
			string name = strFieldValue;
		}
	}
}

mysql_free_result(m_pSQLResultSet);   // 释放资源 
return TRUE;
</pre>
<p><span style="color: rgb(255, 255, 255);">文章来源：</span><a href="http://www.codelast.com/" target="_blank" rel="noopener noreferrer"><span style="color: rgb(255, 255, 255);">http://www.codelast.com/</span></a><br />
上面的代码还不完整，只是演示了怎么读取SQL查询的结果集。但是有了上面的一系列铺垫，你应该可以写出自己的程序来用了。</p>
<p>
<span style="color: rgb(255, 255, 255);">文章来源：</span><a href="https://www.codelast.com/" rel="noopener noreferrer" target="_blank"><span style="color: rgb(255, 255, 255);">https://www.codelast.com/</span></a><br />
<span style="color: rgb(255, 0, 0);">➤➤</span>&nbsp;版权声明&nbsp;<span style="color: rgb(255, 0, 0);">➤➤</span>&nbsp;<br />
转载需注明出处：<u><a href="https://www.codelast.com/" rel="noopener noreferrer" target="_blank"><em><span style="color: rgb(0, 0, 255);"><strong style="font-size: 16px;"><span style="font-family: arial, helvetica, sans-serif;">codelast.com</span></strong></span></em></a></u>&nbsp;<br />
感谢关注我的微信公众号（微信扫一扫）：</p>
<p style="border: 0px; font-size: 13px; margin: 0px 0px 9px; outline: 0px; padding: 0px; color: rgb(77, 77, 77);">
	<img decoding="async" alt="wechat qrcode of codelast" src="https://www.codelast.com/codelast_wechat_qr_code.jpg" style="width: 200px; height: 200px;" /></p>

			<!--[syntaxhighlighter]-->
			<!--代码高亮，请勿编辑-->
			<script type="text/javascript" src="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/scripts/shCore.js"></script><script type="text/javascript" src="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/scripts/shBrushCpp.js"></script>
<script type="text/javascript" src="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/scripts/shBrushPlain.js"></script>

			<link type="text/css" rel="stylesheet" href="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/styles/shCoreCk.css" />
			<link type="text/css" rel="stylesheet" href="https://www.codelast.com/wp-content/plugins/ck-and-syntaxhighlighter/syntaxhighlighter/styles/shThemeCk.css" />
			<script type="text/javascript">
			SyntaxHighlighter.defaults['class-name']	= '';
			SyntaxHighlighter.defaults['smart-tabs']	= true;
			SyntaxHighlighter.defaults['tab-size']		= 2;
			SyntaxHighlighter.defaults['gutter']		= true;
			SyntaxHighlighter.defaults['quick-code']	= true;
			SyntaxHighlighter.defaults['collapse'] 		= false;
			SyntaxHighlighter.defaults['auto-links']	= true;
			SyntaxHighlighter.defaults['toolbar']		= true;
			SyntaxHighlighter.all();
			</script>
			<!--[/syntaxhighlighter]-->]]></content:encoded>
					
					<wfw:commentRss>https://www.codelast.com/%e5%8e%9f%e5%88%9bvc%e8%bf%9e%e6%8e%a5%e6%93%8d%e4%bd%9cmysql%e6%95%b0%e6%8d%ae%e5%ba%93%e9%80%9a%e8%bf%87mysql-c-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
