MYSQL操作类

前序:没有找到以前封装的mysql的操作类,重新又写了一遍,着实让人头疼。希望能帮到大家。

关于相关的配置:
1、将你安装的MYSQL的include目录和lib库,分别加到(以VS举例)VS的包含目录与库目录(属性->VC++ 目录)
2、将libmysql.dll拷贝到你的工程目录下

sqlnet.h

#ifndef __SQLNET_H
#define __SQLNET_H

#ifdef __CLUDESQL
#include "mysql.h"
#else
class MYSQL;
#endif // __CLUDESQL

#include
#include
using namespace std;

typedef int CODE;         // Return code
#define OK 1	              // Success.
#define ERROR_CONNECT 100 // Connect MYSQL database failed.
#define ERROR_QUERY 101   // Query data failed.
#define ERROR_INSERT 102  // Insert data failed.
#define ERROR_DELETE 103  // Delete data failed.
#define ERROR_MODIFY 104  // Modify data failed.

class CMySql
{
public:
	CMySql(const string address, const int port, const string databaseName, const string username, const string password);
	~CMySql();
	
	// Insert data
	CODE Insert(const char* sql);

	// Delete data
	CODE Delete(const char* sql);

	// Modify data
	CODE Modify(const char* sql);

	// Query data
	CODE Query(const char* sql);

	// Get query results
	list<list<string>> GetQueryResults() const { return m_listResult; }
	
	// Get last error
	string GetError() const { return m_strLastError; };

	// Get address
	string GetAddress() const { return m_address; };

	// Get database 
	string GetDatabase() const { return m_database; };

	// Get username
	string GetUsername() const { return m_username; };

	// Get password
	string GetPassword() const { return m_password; };

private:
	int m_port;
	string m_address;
	string m_database;
	string m_username;
	string m_password;
	string m_strLastError;

	MYSQL* mysql;
	list<list<string>> m_listResult;
};

#endif // __SQLNET_H

sqlnet.cpp

#define __CLUDESQL

#include
#include 
#include 
#include "sqlnet.h"
#pragma comment(lib,"libmysql.lib")
using namespace std;


CMySql::CMySql(const string address, const int port, const string database, const string username, const string password)
	:m_address(address), m_port(port), m_database(database), m_username(username), m_password(password)
{
	mysql = new MYSQL();
	assert(mysql != NULL);
	mysql_init(mysql);
	mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "gbk");
}

CMySql::~CMySql()
{
	mysql_close(mysql);
}

CODE CMySql::Insert(const char* sql)
{
	CODE code = OK;

	if (!mysql_real_connect(mysql, m_address.c_str(), m_username.c_str(), m_password.c_str(), m_database.c_str(), m_port, NULL, 0)) {
		m_strLastError = mysql_error(mysql);
		code = ERROR_CONNECT;
	}
	else {
		if (mysql_query(mysql, sql)) {
			m_strLastError = mysql_error(mysql);
			code = ERROR_INSERT;
		}
	}

	mysql_close(mysql);

	return code;
}

CODE CMySql::Delete(const char* sql)
{
	CODE code = OK;

	if (!mysql_real_connect(mysql, m_address.c_str(), m_username.c_str(), m_password.c_str(), m_database.c_str(), m_port, NULL, 0)) {
		m_strLastError = mysql_error(mysql);
		code = ERROR_CONNECT;
	}
	else {
		if (mysql_query(mysql, sql)) {
			m_strLastError = mysql_error(mysql);
			code = ERROR_DELETE;
		}
	}

	mysql_close(mysql);

	return code;
}

CODE CMySql::Modify(const char* sql)
{
	CODE code = OK;

	if (!mysql_real_connect(mysql, m_address.c_str(), m_username.c_str(), m_password.c_str(), m_database.c_str(), m_port, NULL, 0)) {
		m_strLastError = mysql_error(mysql);
		code = ERROR_CONNECT;
	}
	else {
		if (mysql_query(mysql, sql)) {
			m_strLastError = mysql_error(mysql);
			code = ERROR_MODIFY;
		}
	}

	mysql_close(mysql);

	return code;
}


CODE CMySql::Query(const char* sql)
{
	CODE code = OK;

	if (!mysql_real_connect(mysql, m_address.c_str(), m_username.c_str(), m_password.c_str(), m_database.c_str(), m_port, NULL, 0)) {
		m_strLastError = mysql_error(mysql);
		code = ERROR_CONNECT;
	}
	else {
		mysql_query(mysql, "SET NAMES GBK;");
		if (mysql_query(mysql, sql)) {
			m_strLastError = mysql_error(mysql);
			code = ERROR_QUERY;
		}

		MYSQL_RES* result;
		result = mysql_store_result(mysql);
		if (result == NULL) {
			code = OK;
		}
		else {
			// Place the results in a list
			m_listResult.clear();
			MYSQL_ROW row;

			if (mysql_num_rows(result)) {
				// Get a record
				row = mysql_fetch_row(result);
				while (row) {
					// The number of columns
					int count = mysql_field_count(mysql);
					int index = 0;
					list<string> aRecordlist;

					// Adds all the fields in a record to the aRecordlist
					while (index < count) {
						if (row[index] == NULL) {
							aRecordlist.push_back("");
						}
						else {
							aRecordlist.push_back(row[index]);
						}
						++index;
					}

					m_listResult.push_back(aRecordlist);

					row = mysql_fetch_row(result);
				}
			}
		}

		mysql_free_result(result);
	}

	mysql_close(mysql);

	return code;
}

测试程序main.cpp

#include "sql/sqlnet.h"
#include 
using namespace std;

CMySql g_MYSQL("127.0.0.1", 3306, "test", "root", "123456");

void Print(list<list<string>> lls) {
    list<list<string>>::iterator itlls = lls.begin();
    while (itlls != lls.end())
    {
        list<string> item = (*itlls);
        list<string>::iterator itls = item.begin();

        while (itls != item.end()) {
            cout << *itls << ' ';
            ++itls;
        }
        cout << endl;

        itlls++;
    }
}

void Query(string sql) {
    g_MYSQL.Query(sql.c_str());
    Print(g_MYSQL.GetQueryResults());
}

void Insert(string sql) {
    g_MYSQL.Insert(sql.c_str());
}

int main() {
    Query("SELECT * FROM info;");

    Insert("INSERT INTO info (name,id,age) values (\"a\",1,1);");
    
    return 0;
}

如你有更好的建议,请告知,不胜感激!

你可能感兴趣的:(sql)