码迷,mamicode.com
首页 > 数据库 > 详细

C++ MySQL封装类

时间:2015-12-23 14:26:30      阅读:795      评论:0      收藏:0      [点我收藏+]

标签:

#ifndef MYSQL_MANAGER_H
#define MYSQL_MANAGER_H
#include <Winsock2.h>
#include "mysql.h"
#include <string>
#include <vector>
#include <map>
using namespace std;

class mysql_db
{
public:
    mysql_db();
    ~mysql_db();
public:
    /*
        mysql_open()
        return : 1 OK 
                -1 失败  
     */
    int mysql_open(const char * host, const char * user, const char * password, const char * database, unsigned int port );
    /*
        mysql_noResult_query();
        非select语句查询
        return >0 成功, 为受影响的行数
               -1 失败 
     */
    int mysql_noResult_query(const char * sql );
    /*
        mysql_select_query();
        有结果集的查询
        return >0 ok 返回结果集条数
               -1 失败
        map_results first = 行 second = values
        */
    int mysql_select_query(const char * sql, map<int,vector<string>> & map_results);
    /*
        mysql_select_SingleLine_query();
        只有一条数据 , 或者只有一个字段 N 条的查询. 直接调用vector即可
     */
    int mysql_select_SingleLine_query(const char * sql, vector<string> & v_results);
    /*
        mysql_lasterror();
        返回最近一次错误信息
     */
    string mysql_lasterror();
private:
    MYSQL sqlCon;
    MYSQL_RES *m_pResult;
    MYSQL_ROW  m_Row;
};

#endif
#include "stdafx.h"
#include "managesql.h"

mysql_db::mysql_db()
{
    mysql_init(&sqlCon);// mysql 初始化
}
mysql_db::~mysql_db()
{
    mysql_close(&sqlCon);// 关闭连接
}

int mysql_db::mysql_open(const char * host, const char * user, const char * password, const char * database, unsigned int port)
{
    char nvalue = 1;
    mysql_options(&sqlCon, MYSQL_OPT_RECONNECT, (char *)&nvalue);// 断线自动重连
    mysql_options(&sqlCon, MYSQL_SET_CHARSET_NAME, "gbk");// set name gbk 中文乱码问题
    if (!mysql_real_connect(&sqlCon, host, user, password, database, port, NULL, 0)){
        return -1;
    }
    return 1;
}

int mysql_db::mysql_noResult_query(const char * sql)
{
    if (mysql_query(&sqlCon, sql) != 0){
        return -1;
    }
    return (int)mysql_affected_rows(&sqlCon);
}

int mysql_db::mysql_select_query(const char * sql, map<int, vector<string>> & map_results)
{
    if (mysql_query(&sqlCon, sql) != 0){
        return -1;
    }

    if(!(m_pResult = mysql_use_result(&sqlCon))){
        return -1;
    }
    int i = 0;

    int count = mysql_num_fields(m_pResult);
    while(m_Row = mysql_fetch_row(m_pResult)){
        vector<string> vVal;
        for (int j = 0; j < count; j++){
            vVal.push_back(m_Row[j]);
        }
        map_results[i++] = vVal;
    }
    mysql_free_result(m_pResult);
    return i;
}

int mysql_db::mysql_select_SingleLine_query(const char * sql, vector<string> & v_results)
{
    if (mysql_query(&sqlCon, sql) != 0){
        return -1;
    }
    if(!(m_pResult = mysql_use_result(&sqlCon))){
        return -1;
    }
    int i = 0;

    int count = mysql_num_fields(m_pResult);
    while(m_Row = mysql_fetch_row(m_pResult)){
        for (int j = 0; j < count; j++){
            v_results.push_back(m_Row[j]);
        }
    }
    mysql_free_result(m_pResult);
    return i;
}

string mysql_db::mysql_lasterror()
{
    return mysql_error(&sqlCon);
}
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "ManageSQL.h"
#include <vld.h>
using namespace std;

int main()
{
    mysql_db mydb;

    //打开.. 连接
    if (-1 == mydb.mysql_open("Localhost", "root", "123456", "electronicpolice", MYSQL_PORT))
        cout << mydb.mysql_lasterror() << endl;

    //创建一个库
    string sql = "create database if not exists database_test";
    if ( -1 == mydb.mysql_noResult_query(sql.c_str()))
        cout << mydb.mysql_lasterror() << endl;

    //use 库
    sql = "use database_test";
    if ( -1 == mydb.mysql_noResult_query(sql.c_str()))
        cout << mydb.mysql_lasterror() << endl;

    //创建一张表
    sql = "create table if not exists table_test(id int not null auto_increment, name varchar(20) not null, age int not null ,primary key (id) )";
    if ( -1 == mydb.mysql_noResult_query(sql.c_str()))
        cout << mydb.mysql_lasterror() << endl;

    //插入2条数据
    sql = "insert into table_test (name,age) values(‘newsoul‘,‘25‘)";
    if ( -1 == mydb.mysql_noResult_query(sql.c_str()))
        cout << mydb.mysql_lasterror() << endl;
    sql = "insert into table_test (name,age) values(‘百度‘,‘100‘)";
    if ( -1 == mydb.mysql_noResult_query(sql.c_str()))
        cout << mydb.mysql_lasterror() << endl;


    //mysql_select_SingleLine_query 演示
    sql = "select * from table_test where id=1 ";
    vector<string> vResults;
    if (-1 == mydb.mysql_select_SingleLine_query(sql.c_str(),vResults))
        cout << mydb.mysql_lasterror() << endl;

    //遍历结果集
    cout << "select * from table_test where id=1的结果: " << endl;
    for (vector<string>::iterator it = vResults.begin(); it != vResults.end(); it++)
        cout << (*it) << endl;


    cout << endl << endl;
    //mysql_select_query 演示
    sql = "select * from table_test";

    int i = 0;
    while (i++ < 100){
        map<int,vector<string>> map_res;
        if (-1 == mydb.mysql_select_query(sql.c_str(),map_res))
            cout << mydb.mysql_lasterror() << endl;


        //遍历...
        cout << "select * from table_test的结果:" << endl;
        for (map<int,vector<string>>::iterator it = map_res.begin(); it != map_res.end(); it++){
            cout << "" << it->first+1<< "条 : ";
            for (int i=0;i<it->second.size();i++)
            {
                cout << it->second[i] << "\t";
            }
            cout << endl;
        }
    }
    
    system("pause");
    return 0;
}

 

C++ MySQL封装类

标签:

原文地址:http://www.cnblogs.com/qq76211822/p/5069612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!