---
title: "Linux下使用C/C++访问数据库"
author: "sealbird"
date: "2011-01-07T16:19:37Z"
tags: ["C", "C#", "C++", "Linux", "MySQL"]
categories: ["编程语言"]
slug: "linux-c-c"
draft: false
lastmod: "2011-01-10T11:41:38Z"
id: 865355
url: "https://sealbird.iteye.com/blog/865355"
---

Linux下使用C/C++访问数据库——MySQL篇 最近打算写一套OA系统，为了方便进行数据库操作，特意抽出一周的时间来研究C/C++访问各种数据库的方法，并打算封装一套数据库操作类，现在奉上最简单的一部分：在Linux下访问MySQL数据库。 本文中使用的MySQL API代码为C语言，如果各位对C++有兴趣，可以考虑使用mysql++。 一、配置开发环境 首先需要编译、安装MySQL，安装完成后，将MySQL目录中的lib目录添加到环境变量中。 新建C/C++工程，把$MYSQL\_ROOT/include添加到编译环境的包含路径下面。在编译选项中，增加$MYSQL\_ROOT/lib目录。在Link选项中增加-lmysqlclient（已经把lib目录增加到系统环境变量中），或者直接引用libmysqlclient.so文件。 二、程序代码 不多说了，直接上代码，注释都很详细。 \[code="c++"]/* * MySQLManager.h * * Created on: Feb 18, 2009 * Author: Steven Wee \*/ #ifndef MYSQLMANAGER\_H_ #define MYSQLMANAGER\_H_ #include "../Common/CheckStringTools.h" #include #include #include #include #include using namespace std; class MySQLManager { public: /* * Init MySQL * @param hosts: Host IP address * @param userName: Login UserName * @param password: Login Password * @param dbName: Database Name * @param port: Host listen port number \*/ MySQLManager(std::string hosts, std::string userName, std::string password, std::string dbName, unsigned int port); ~MySQLManager(); void initConnection(); /* * Making query from database * @param mysql: MySQL Object * @param sql: Running SQL command \*/ bool runSQLCommand(std::string sql); /\** * Destroy MySQL object * @param mysql MySQL object \*/ void destroyConnection(); bool getConnectionStatus(); vector&lt; vector &gt; getResult(); protected: void setUserName(std::string userName); void setHosts(std::string hosts); void setPassword(std::string password); void setDBName(std::string dbName); void setPort(unsigned int port); private: bool IsConnected; vector&lt; vector &gt; resultList; MYSQL mySQLClient; unsigned int DEFAULTPORT; char * HOSTS; char * USERNAME; char * PASSWORD; char * DBNAME; }; #endif /* MYSQLMANAGER\_H_ \*/ /* * MySQLManager.cpp * * Created on: Feb 18, 2009 * Author: Steven Wee \*/ #include "MySQLManager.h" MySQLManager::MySQLManager(string hosts, string userName, string password, string dbName, unsigned int port) { IsConnected = false; this -&gt;setHosts(hosts); // 设置主机IP地址 this -&gt;setUserName(userName); // 设置登录用户名 this -&gt;setPassword(password); // 设置登录密码 this -&gt;setDBName(dbName); // 设置数据库名 this -&gt;setPort(port); // 设置端口号 } MySQLManager::~MySQLManager() { this -&gt;destroyConnection(); } void MySQLManager::setDBName(string dbName) { if ( dbName.empty() ) {// 用户没有指定数据库名 std::cout &lt;&lt; "DBName is null! Used default value: mysql" &lt;&lt; std::endl; this -&gt;DBNAME = new char\[5]; strcpy(this -&gt;DBNAME, "mysql"); } else { this -&gt;DBNAME = new char\[dbName.length()]; strcpy(this -&gt;DBNAME, dbName.c\_str()); } } void MySQLManager::setHosts(string hosts) { if ( hosts.empty() ) {// 用户没有指定数据库IP地址 std::cout &lt;&lt; "Hosts is null! Used default value: localhost" &lt;&lt; std::endl; this -&gt;HOSTS = new char\[9]; strcpy(this -&gt;HOSTS, "localhost"); } else { this -&gt;HOSTS = new char\[hosts.length()]; strcpy(this -&gt;HOSTS, hosts.c\_str()); } } void MySQLManager::setPassword(string password) {// 用户没有指定密码 if ( password.empty() ) { std::cout &lt;&lt; "Password is null! Used default value: " &lt;&lt; std::endl; this -&gt;PASSWORD = new char\[1]; strcpy(this -&gt;PASSWORD, ""); } else { this -&gt;PASSWORD = new char\[password.length()]; strcpy(this -&gt;PASSWORD, password.c\_str()); } } void MySQLManager::setPort(unsigned int port) {// 用户没有指定端口号，使用默认端口号 if ( port ) { std::cout &lt;&lt; "Port number is null! Used default value: 0" &lt;&lt; std::endl; this -&gt;DEFAULTPORT = 0; } else { this -&gt;DEFAULTPORT = port; } } void MySQLManager::setUserName(string userName) {// 用户没有指定登录用户名 if ( userName.empty() ) { std::cout &lt;&lt; "UserName is null! Used default value: root" &lt;&lt; std::endl; this -&gt;USERNAME = new char\[4]; strcpy(this -&gt;USERNAME, "root"); } else { this -&gt;USERNAME = new char\[userName.length()]; strcpy(this -&gt;USERNAME, userName.c\_str()); } } void MySQLManager::initConnection() { if ( IsConnected ) {// 已经连接到服务器 std::cout &lt;&lt; "Is connected to server!" &lt; objectValue; while( (row = mysql\_fetch\_row(res)) ) {// 遍历结果集 objectValue.clear(); for ( j = 0 ; j &lt; mysql\_num\_fields(res) ; j++ ) { objectValue.push\_back(row\[j]); } this -&gt;resultList.push\_back(objectValue); } mysql\_free\_result(res); //free result after you get the result return true; } vector&lt; vector &gt; MySQLManager::getResult() { return resultList; } void MySQLManager::destroyConnection() { mysql\_close(&mySQLClient); this -&gt;IsConnected = false; } bool MySQLManager::getConnectionStatus() { return IsConnected; } \[/code] 三、修改建议 本人在以后的完善中，打算把runSQLCommand(char * sql)函数分解成两个或者三个函数，分别执行select和insert等语句。 在程序中，我并没有强制要求参数必须为const，可能会出现一些安全问题。 本文仅起抛砖引玉的作用，希望有高手可以指点我程序中的问题。 敬请期待下一篇文章：Linux下使用C/C++访问数据库——SQL Server篇 一个例子 \[code="c++"]#include #include #include using namespace std; class CBaseX { public: int x; CBaseX() { x = 10; } void foo() { printf("CBaseX::foo() x=%d\\n", x); } }; class CBaseY { public: int y; int* py; CBaseY() { y = 20; py = &y; } void bar() { printf("CBaseY::bar() y=%d, \*py=%d\\n", y, \*py); } }; class CDerived : public CBaseX, public CBaseY { public: int z; CDerived() { z = 10; } void test() { printf("test z=%d\\n", z); } }; int main() { int n = 65535; strstream ss; strstream ss1; strstream ss2; string s; string s1; string s2; ss &lt;&lt; n; ss &gt;&gt; s; cout &lt;&lt; s &lt;&lt; endl; double t\_d = 10.6; float t\_i= static\_cast(t\_d); // cout&lt;&gt;s1; cout &lt;&lt; s1 &lt;&lt; endl; char* c="iloveyou"; char * p = reinterpret\_cast(c);// ss2&lt;&gt;s2; cout &lt;&lt; s2 &lt;&lt; endl; CDerived* pD = new CDerived(); // pD-&gt;bar(); printf("CDerived* pD = %x\\n", (int)pD); CBaseY* pY = pD; // 成功编译, pY = pD + 4 // pY-&gt;bar(); CBaseY* pD3 = dynamic\_cast(pD);// pD3-&gt;bar(); CDerived* pD4 = static\_cast(pD3);// pD4-&gt;bar(); CBaseY* pD5 = static\_cast(pD4);// pD5-&gt;bar(); CDerived* pD6 = reinterpret\_cast(pD4);// 出错 pD6-&gt;bar(); printf("CBaseY* pY = %x\\n", (int)pY); void* pV1 = pY; //成功编译, pV1 = pY printf("void* pV1 = %x\\n", (int)pV1); // pD2 = pY, 但是我们预期 pD2 = pY - 4 CDerived* pD2 = static\_cast(pV1); printf("CDerived* pD2 = %x\\n", (int)pD2); // 系统崩溃 pD2-&gt;test(); /* class B {}; class D: public B {} void f( B* pb ) { D* pd1 = dynamic\_cast(pb); D* pd2 = static\_cast(pb); }\*/ return 0; } /* dynamic\_cast:向下转型 static\_cast :这个好用 ,可向上也可向下 reinterpret\_cast: 这个还有待进一步体会 const\_cast: 这个也要时一步体会真实用法 \*/ \[/code]