c++ 简单封装mysql数据库连接类 实例

在c++开发过程中,我们可能会用到mysql数据库,这边我简单写了一个类似PHP封装的mysql类,希望能帮助像我这样的C++初学者。

首先我们要安装mysql c++ 库下载地址

http://dev.mysql.com/downloads/connector/cpp/

我的环境是centos5.5

安装完毕后 看代码:

 

 

#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class mysql_database
{
        private:
                string  db_host;
                string  db_name;
                string  db_user;
                string  db_passwd;
                string  db_charset;
                string  db_port;

                sql::Driver *driver;
                sql::Connection *con;
                sql::Statement *stmt;
                sql::ResultSet *result;

        public:
                mysql_database(map<string,string> &conf) :
                        driver(NULL),con(NULL),stmt(NULL),result(NULL)
                {
                        db_host=conf["db_host"];
                        db_name=conf["db_name"];
                        db_user=conf["db_user"];
                        db_passwd=conf["db_passwd"];
                        db_port=conf["db_port"];
                        db_charset=conf["db_charset"];

                }
                sql::Connection  *db_connect(string database="")
                {
                        try{
                                string db;
                                db=(database=="")?db_name:database;
                                driver = get_driver_instance();
                                //cout<<db_host<<db_port<<db_user<<db_passwd<<db_name<<endl;
                                con = driver->connect("tcp://"+db_host+":"+db_port, db_user, db_passwd);
                                con->setSchema(db);
                                this->squery("SET NAMES "+db_charset);
                                return con;
                        }
                        catch (sql::SQLException &e)
                        {
                                cout << "# ERR: SQLException in " << __FILE__;
                                cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;
                                cout << "# ERR: " << e.what();
                                cout << " (MySQL error code: " << e.getErrorCode();
                                cout << ", SQLState: " << e.getSQLState() << " )" << endl;
                        }

                }

                /**
                * simple query for  create/update/delete
                * @param string sql
                * @return bool  TRUE OR FALS
                */
                bool squery(string sql)
                {
                        stmt = con->createStatement();
                        return stmt->execute(sql);
                }
                sql::ResultSet *query(string sql)
                {
                        stmt = con->createStatement();
                        result=stmt->executeQuery(sql);
                        return result;
                }
                /* retrieve the row count in the result set */
                int get_total(sql::ResultSet *result)
                {
                        int total;
                        total=result->rowsCount();
                        return total;
                }
                /**
                * fetch query rows
                * @param result
                * @param field          the db table's field for this query
                * @return mutil_map     
                */
                map<int,map<string,string> > fetch_map(sql::ResultSet *result,map<string,string>field)
                {
                        /* fetch the data : retrieve all the rows in the result set */
                        map<int,map<string,string> > data;
                        map<string,string>::iterator  it;
                        int k=0;
                        if((!field.empty())&&(field.size()>0))
                        {
                                while(result->next())
                                {
                                        map<string,string> row;
                                        for ( it=field.begin() ; it!=field.end() ;it++ )
                                                row[it->first]=result->getString(it->second);
                                        data[k]=row;
                                        k++;
                                }
                        }

                        return data ;

                }

};

 

用法如下:

 

#include<iostream>
#include<string>
#include<stdlib.h>
#include<map>
#include <boost/date_time.hpp>
#include "mysql_database.h"
#include "parase_ini.h"
using namespace boost;
using namespace std;
int main()
{
        parase_ini conf("config.ini");
        map<string,string> config=conf.get_config();
        mysql_database db (config);
        db.db_connect();
        sql::ResultSet * rs;
        map<string,string> field ;
        field["0"]="v_name" ;//
        rs=db.query("select v_name  from  pi_data  limit 1 ");
        map<int,map<string,string> > rows;
        rows=db.fetch_map(rs,field);
        map<int,map<string,string> >::iterator  it;
        for (it=rows.begin();it!=rows.end();it++)
        {
                map<string,string>::iterator item;
                map<string,string> content;
                content=it->second;
                for (item=content.begin();item!=content.end();item++)
                {
                        cout<<item->second<<endl;
                }
        }
        //----------- db2 start -----------
        db.db_connect("df17db");
        field["0"]="username";
        field["1"]="name";
        rs=db.query("select *  from zhuna_admin");
        rows=db.fetch_map(rs,field);
        for (it=rows.begin();it!=rows.end();it++)
        {
                map<string,string>::iterator item;
                map<string,string> content;
                content=it->second;
                string str;
                for (item=content.begin();item!=content.end();item++)
                {
                        //cout<<item->second<<endl;
                        str+=item->second+"\t";
                }
                str+="\n";
                cout<<str<<endl;
        }
        //------------ db2 end ---------------



}


说明 :上面的用法可能有其他模块 ,同学们看数据库调用就行 了。

 

 

你可能感兴趣的:(mysql)