search

MySQL的C++封装

Jun 07, 2016 pm 03:41 PM
c++mysqlencapsulationdatabasemanagement systemproject

最近的项目数据库管理系统从SQL SERVER2000迁移到了MySQL上来,之前基于ADO的连接方式连接上SQL SERVER,使用MySQL数据库管理系统之后,直接在MySQL的C语言的API上以面向对象的方式封装实现了数据库的创建,表的创建,数据库的读写操作快速搭建原型,目前没

最近的项目数据库管理系统从SQL SERVER2000迁移到了MySQL上来,之前基于ADO的连接方式连接上SQL SERVER,使用MySQL数据库管理系统之后,直接在MySQL的C语言的API上以面向对象的方式封装实现了数据库的创建,表的创建,数据库的读写操作快速搭建原型,目前没有添加连接池模块和事务处理。


源码托管在github上:https://github.com/figot/MySQLWrapper

1.MySQL的特性

使用C和C++编写,并使用了多种编译器进行测试,保证源代码的可移植性。
支持AIX、BSDi、FreeBSD、HP-UX、Linux、Mac OS、Novell NetWare、NetBSD、OpenBSD、OS/2 Wrap、Solaris、Windows等多种操作系统。
为多种編程语言提供了API。这些編程语言包括C、C++、C#、VB.NET、Delphi、Eiffel、Java、Perl、PHP、Python、Ruby和Tcl等。
支持多線程,充分利用CPU资源,支持多用户。
優化的SQL查询算法,有效地提高查询速度。
既能够作为一个单独的应用程序在客户端服务器网络环境中运行,也能够作为一个程序库而嵌入到其他的软件中。
提供多语言支持,常见的编码如中文的GB 2312、BIG5,日文的Shift JIS等都可以用作數據表名和數據列名。
提供TCP/IP、ODBC和JDBC等多种数据库连接途径。
提供用于管理、检查、优化数据库操作的管理工具。
可以处理拥有上千万条记录的大型数据库。

2.C++的API封装

用C++连接SQL有两种可直接使用的接口:MySQL Connector/C++和MySQL+ +,MySQL Connector/C++是最新发布的MySQL连接器,由Sun Microsystems开发。MySQL connector为C++提供面向对象的编程接口(API)和连接MySQL Server的数据库驱动器与现存的driver不同,Connector/C++是JDBC API在C++中的实现。换句话说,Connector/C++ driver的接口主要是基于Java语言的JDBC API。Java数据库连接(JDBC)是Java连接各种数据库的业界标准。Connector/C++实现了JDBC 4.0的大部分规范。熟悉JDBC编程的C++程序开发者可以提高程序开发的效率。

MySQL++是一个用C++封装了MySQL的C API的类库。它是建立标准C ++标准库(STL)之上,使处理数据库处理STL容器一样容易。此外,MySQL的++提供了让你避免最重复的工作,提供了原生C++接口。

3.MySQL的C++封装实现

在快速搭建原型的过程中,没有用到这两种连接方式,直接在MySQL C API上封装实现。

#ifndef __MYSQL_INTERFACE_H__
#define __MYSQL_INTERFACE_H__

#include "winsock.h"
#include <iostream>
#include <string>
#include "mysql.h"
#include <vector>
#include <string>

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "libmysql.lib")
using namespace std;

class MySQLInterface
{
public:  
	MySQLInterface();
	virtual ~MySQLInterface();

	bool connectMySQL(char* server, char* username, char* password, char* database,int port);
	bool createDatabase(std::string& dbname);
	bool createdbTable(const std::string& query);

	void errorIntoMySQL();
	bool writeDataToDB(string queryStr);
	bool getDatafromDB(string queryStr, std::vector<:vector> >& data);
	void closeMySQL();

public:
	int errorNum;                    //错误代号
	const char* errorInfo;             //错误提示

private:
	MYSQL mysqlInstance;                      //MySQL对象,必备的一个数据结构
	MYSQL_RES *result;                 //用于存放结果 建议用char* 数组将此结果转存
};

#endif</:vector></string></vector></string></iostream>


#include "stdafx.h"
#include "MySQLInterface.h"


//构造函数 初始化各个变量和数据
MySQLInterface::MySQLInterface():
	errorNum(0),errorInfo("ok")
{
	mysql_library_init(0,NULL,NULL);
	mysql_init(&mysqlInstance);
	mysql_options(&mysqlInstance,MYSQL_SET_CHARSET_NAME,"gbk");
}

MySQLInterface::~MySQLInterface()
{

}

//连接MySQL
bool MySQLInterface::connectMySQL(char* server, char* username, char* password, char* database,int port)
{
	if(mysql_real_connect(&mysqlInstance,server,username,password,database,port,0,0) != NULL)
		return true;
	else
		errorIntoMySQL();
	return false;
}
//判断数据库是否存在,不存在则创建数据库,并打开
bool MySQLInterface::createDatabase(std::string& dbname)
{
	std::string queryStr = "create database if not exists ";
	queryStr += dbname;
	if (0 == mysql_query(&mysqlInstance,queryStr.c_str()))
	{
		queryStr = "use ";
		queryStr += dbname;
		if (0 == mysql_query(&mysqlInstance,queryStr.c_str()))
		{
			return true;
		}
		
	}
	errorIntoMySQL();
	return false;
}
//判断数据库中是否存在相应表,不存在则创建表
bool MySQLInterface::createdbTable(const std::string& query)
{
	if (0 == mysql_query(&mysqlInstance,query.c_str()))
	{
		return true;
	}
	errorIntoMySQL();
	return false;
}

//写入数据
bool MySQLInterface::writeDataToDB(string queryStr)
{
	if(0==mysql_query(&mysqlInstance,queryStr.c_str()))
		return true;
	else
		errorIntoMySQL();
	return false;	
}
//读取数据
bool MySQLInterface::getDatafromDB(string queryStr, std::vector<:vector> >& data)
{
	if(0!=mysql_query(&mysqlInstance,queryStr.c_str()))
	{
		errorIntoMySQL();
		return false;
	}

	result=mysql_store_result(&mysqlInstance);

	int row=mysql_num_rows(result);
	int field=mysql_num_fields(result);

	MYSQL_ROW line=NULL;
	line=mysql_fetch_row(result);

	int j=0;
	std::string temp;
	while(NULL!=line)
	{	
		std::vector<:string> linedata;
		for(int i=0; i<field if temp="line[i];" linedata.push_back else line="mysql_fetch_row(result);" data.push_back return true void mysqlinterface::errorintomysql errornum="mysql_errno(&mysqlInstance);" errorinfo="mysql_error(&mysqlInstance);" mysqlinterface::closemysql mysql_close><br>
<br>


</field></:string></:vector>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools