欢迎您访问我爱IT技术网,今天小编为你分享的编程技术是:【实例讲解如何使用C++操作MySQL数据库类】,下面是详细的分享!
实例讲解如何使用C++操作MySQL数据库类
用C++操作MySQL数据库类:
注释:这几个类对处理不是很大数据量的操作是很理想的, 但不适宜特大型的数据的查询,因为源码中将查询到的数据直接放入了内存。
#ifndef ZLB_MYSQL_H
#define ZLB_MYSQL_H
#include "mysql.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
namespace zlb_mysql{
class Field
{
public :
vector<string> m_name;
vector<enum_field_types> m_type;
public :
Field();
~Field();
bool IsNum(int num);
bool IsNum(string num);
bool IsDate(int num);
bool IsDate(string num);
bool IsChar(int num);
bool IsChar(string num);
bool IsBlob(int num);
bool IsBlob(string num);
int GetField_NO(string field_name);
};
class Record
{
public:
vector<string> m_rs;
Field *m_field;
public :
Record(){};
Record(Field* m_f);
~Record();
void SetData(string value);
string operator[](string s);
string operator[](int num);
bool IsNull(int num);
bool IsNull(string s);
string GetTabText();
};
class RecordSet
{
private :
vector<Record> m_s;
unsigned long pos;
int m_recordcount;
int m_field_num;
Field m_field;
MYSQL_RES * res ;
MYSQL_FIELD * fd ;
MYSQL_ROW row;
MYSQL* m_Data ;
public :
RecordSet();
RecordSet(MYSQL *hSQL);
~RecordSet();
int ExecuteSQL(const char *SQL);
int GetRecordCount();
int GetFieldNum();
long MoveNext();
long Move(long length);
bool MoveFirst();
bool MoveLast();
unsigned long GetCurrentPos()const;
bool GetCurrentFieldValue(const char * sFieldName,char *sValue);
bool GetCurrentFieldValue(const int iFieldNum,char *sValue);
bool GetFieldValue(long index,const char * sFieldName,char *sValue);
bool GetFieldValue(long index,int iFieldNum,char *sValue);
bool IsEof();
Field* GetField();
const char * GetFieldName(int iNum);
const int GetFieldType(char * sName);
const int GetFieldType(int iNum);
Record operator[](int num);
};
class DataBase
{
public :
DataBase();
~DataBase();
private :
MYSQL* m_Data;
public :
MYSQL * GetMysql();
int Connect(string host, string user,
string passwd, string db,
unsigned int port,
unsigned long client_flag);
void DisConnect();
int ExecQuery(string sql);
int Ping();
int ShutDown();
int ReBoot();
int Start_Transaction();
int Commit();
int Rollback();
const char * Get_client_info();
const unsigned long Get_client_version();
const char * Get_host_info();
const char * Get_server_info();
const unsigned long Get_server_version();
const char * Get_character_set_name();
char * ExecQueryGetSingValue(string sql);
const char * GetSysTime();
int Create_db(string name);
int Drop_db(string name);
};
};
#endif //ZLB_MYSQL_H
#include "stdafx.h"
#include "zlb_mysql.h"
namespace zlb_mysql{
Field::Field(){}
Field::~Field(){}
bool Field::IsNum(int num)
{
if(IS_NUM(m_type[num]))
return true;
else
return false;
}
bool Field::IsNum(string num)
{
if(IS_NUM(m_type[GetField_NO(num)]))
return true;
else
return false;
}
bool Field::IsDate(int num)
{
if( FIELD_TYPE_DATE==m_type[num] ||
FIELD_TYPE_DATETIME==m_type[num] )
return true;
else
return false;
}
bool Field::IsDate(string num)
{
int temp;
temp=GetField_NO(num);
if(FIELD_TYPE_DATE==m_type[temp] ||
FIELD_TYPE_DATETIME==m_type[temp] )
return true;
else
return false;
}
bool Field::IsChar(int num)
{
if(m_type[num]==FIELD_TYPE_STRING ||
m_type[num]==FIELD_TYPE_VAR_STRING ||
m_type[num]==FIELD_TYPE_CHAR )
return true;
else
return false;
}
bool Field::IsChar(string num)
{
int temp;
temp=this->GetField_NO (num);
if(m_type[temp]==FIELD_TYPE_STRING ||
m_type[temp]==FIELD_TYPE_VAR_STRING ||
m_type[temp]==FIELD_TYPE_CHAR )
return true;
else
return false;
}
bool Field::IsBlob(int num)
{
if(IS_BLOB(m_type[num]))
return true;
else
return false;
}
bool Field::IsBlob(string num)
{
if(IS_BLOB(m_type[GetField_NO(num)]))
return true;
else
return false;
}
int Field::GetField_NO(string field_name)
{
for(unsigned int i=0;i<m_name.size ();i++)
{
if(!m_name[i].compare (field_name))
return i;
}
return -1;
}
Record::Record(Field * m_f)
{
m_field=m_f;
}
Record::~Record(){};
void Record::SetData(string value)
{
m_rs.push_back (value);
}
string Record::operator[](string s)
{
return m_rs[m_field->GetField_NO(s)];
}
string Record::operator[](int num)
{
return m_rs[num];
}
bool Record::IsNull(int num)
{
if(""==m_rs[num].c_str ())
return true;
else
return false;
}
bool Record::IsNull(string s)
{
if(""==m_rs[m_field->GetField_NO(s)].c_str())
return true;
else return false;
}
string Record::GetTabText()
{
string temp;
for(unsigned int i=0 ;i<m_rs.size();i++)
{
temp+=m_rs[i];
if(i<m_rs.size ()-1)
temp+="\t";
}
return temp;
}
RecordSet::RecordSet()
{
res=NULL;
row=NULL;
pos=0;
}
RecordSet::RecordSet(MYSQL *hSQL)
{
res=NULL;
row=NULL;
m_Data=hSQL;
pos=0;
}
RecordSet::~RecordSet()
{
}
int RecordSet::ExecuteSQL(const char *SQL)
{
if ( !mysql_real_query(m_Data,SQL,strlen(SQL)))
{
//保存查询结果
res=mysql_store_result(m_Data );
//得到记录数量
m_recordcount=(int)mysql_num_rows(res) ;
//得到字段数量
m_field_num=mysql_num_fields(res) ;
for (int x=0 ; fd=mysql_fetch_field(res); x++)
{
m_field.m_name.push_back(fd->name);
m_field.m_type.push_back(fd->type);
}
//保存所有数据
while (row=mysql_fetch_row(res))
{
Record temp(&m_field);
for (int k=0 ; k < m_field_num ; k++ )
{
if(row[k]==NULL||(!strlen(row[k])))
{
temp.SetData ("");
}
else
{
temp.SetData(row[k]);
}
}
//添加新记录
m_s.push_back (temp);
}
mysql_free_result(res ) ;
return m_s.size();
}
return -1;
}
long RecordSet::MoveNext()
{
return (++pos);
}
long RecordSet::Move(long length)
{
int l=pos + length;
if(l<0)
{
pos=0;
return 0;
}else
{
if(l >=m_s.size())
{
pos=m_s.size()-1;
return pos;
}else
{
pos=l;
return pos;
}
}
}
bool RecordSet::MoveFirst()
{
pos=0;
return true;
}
bool RecordSet::MoveLast()
{
pos=m_s.size()-1;
return true;
}
unsigned long RecordSet::GetCurrentPos()const
{
return pos;
}
bool RecordSet::GetCurrentFieldValue(const char * sFieldName,
char *sValue)
{
strcpy(sValue,m_s[pos][sFieldName].c_str());
return true;
}
bool RecordSet::GetCurrentFieldValue(const int iFieldNum,char *sValue)
{
strcpy(sValue,m_s[pos][iFieldNum].c_str());
return true;
}
bool RecordSet::GetFieldValue(long index,const char * sFieldName,
char *sValue)
{
strcpy(sValue,m_s[index][sFieldName].c_str());
return true;
}
bool RecordSet::GetFieldValue(long index,int iFieldNum,char *sValue)
{
strcpy(sValue,m_s[index][iFieldNum].c_str());
return true;
}
bool RecordSet::IsEof()
{
return (pos==m_s.size())?true:false;
}
int RecordSet::GetRecordCount()
{
return m_recordcount;
}
int RecordSet::GetFieldNum()
{
return m_field_num;
}
Field * RecordSet::GetField()
{
return &m_field;
}
const char * RecordSet::GetFieldName(int iNum)
{
return m_field.m_name.at(iNum).c_str();
}
const int RecordSet::GetFieldType(char * sName)
{
int i=m_field.GetField_NO(sName);
return m_field.m_type.at(i);
}
const int RecordSet::GetFieldType(int iNum)
{
return m_field.m_type.at(iNum);
}
Record RecordSet::operator[](int num)
{
return m_s[num];
}
DataBase::DataBase()
{
m_Data=NULL;
}
DataBase::~DataBase()
{
if(NULL !=m_Data)
{
DisConnect();
}
}
MYSQL * DataBase::GetMysql()
{
return m_Data;
}
int DataBase::Connect(string host, string user,
string passwd, string db,
unsigned int port,
unsigned long client_flag)
{
if((m_Data=mysql_init(NULL)) &&
mysql_real_connect( m_Data, host.c_str(),
user.c_str(), passwd.c_str(),
db.c_str(),port , NULL,
client_flag))
{
//选择制定的数据库失败
if ( mysql_select_db( m_Data, db.c_str () ) < 0 )
{
mysql_close( m_Data) ;
return -1 ;
}
}
else
{
//初始化mysql结构失败
mysql_close( m_Data );
return -1 ;
}
//成功
return 0;
}
void DataBase::DisConnect( )
{
mysql_close(m_Data) ;
}
int DataBase::ExecQuery(string sql)
{
if(!mysql_real_query(m_Data,sql.c_str (),(unsigned long)sql.length()) )
{
//得到受影响的行数
return (int)mysql_affected_rows(m_Data) ;
}
else
{
//执行查询失败
return -1;
}
}
int DataBase::Ping()
{
if(!mysql_ping(m_Data))
return 0;
else
return -1;
}
int DataBase::ShutDown()
{
if(!mysql_shutdown(m_Data,SHUTDOWN_DEFAULT))
return 0;
else
return -1;
}
int DataBase::ReBoot()
{
if(!mysql_reload(m_Data))
return 0;
else
return -1;
}
int DataBase::Start_Transaction()
{
if(!mysql_real_query(m_Data, "START TRANSACTION" ,
(unsigned long)strlen("START TRANSACTION") ))
{
return 0;
}
else
//执行查询失败
return -1;
}
int DataBase::Commit()
{
if(!mysql_real_query( m_Data, "COMMIT",
(unsigned long)strlen("COMMIT") ) )
{
return 0;
}
else
//执行查询失败
return -1;
}
int DataBase::Rollback()
{
if(!mysql_real_query(m_Data, "ROLLBACK",
(unsigned long)strlen("ROLLBACK") ) )
return 0;
else
//执行查询失败
return -1;
}
const char * DataBase::Get_client_info()
{
return mysql_get_client_info();
}
const unsigned long DataBase::Get_client_version()
{
return mysql_get_client_version();
}
const char * DataBase::Get_host_info()
{
return mysql_get_host_info(m_Data);
}
const char * DataBase::Get_server_info()
{
return mysql_get_server_info( m_Data );
}
const unsigned long DataBase::Get_server_version()
{
return mysql_get_server_version(m_Data);
}
const char * DataBase::Get_character_set_name()
{
return mysql_character_set_name(m_Data);
}
char * DataBase::ExecQueryGetSingValue(string sql)
{
MYSQL_RES * res;
MYSQL_ROW row ;
char *p=NULL;
if(!mysql_real_query( m_Data, sql.c_str(),(unsigned long)sql.length()))
{
//保存查询结果
res=mysql_store_result( m_Data ) ;
row=mysql_fetch_row( res ) ;
p=((row[0]==NULL)||(!strlen(row[0])))?"-1":row[0];
mysql_free_result( res ) ;
}
else
//执行查询失败
p="-1";
return p;
}
const char * DataBase::GetSysTime()
{
return ExecQueryGetSingValue("select now()");
}
int DataBase::Create_db(string name)
{
string temp ;
temp="CREATE DATABASE ";
temp+=name;
if(!mysql_real_query( m_Data,temp.c_str () ,
(unsigned long)temp.length ()) )
return 0;
else
//执行查询失败
return -1;
}
int DataBase::Drop_db(string name)
{
string temp ;
temp="DROP DATABASE ";
temp+=name;
if(!mysql_real_query( m_Data,temp.c_str () ,
(unsigned long)temp.length ()) )
return 0;
else
//执行查询失败
return -1;
}
};
#include "zlb_mysql.h"
using namespace std;
void main()
{
zlb_mysql::DataBase zlb;
//连接数据库
if(-1==zlb.Connect("localhost",
"root","apple",
"test",
0,0))
{
std::cout<<"connect failed "<<std::endl;
}
else
{
std::cout<<"connect success"<<std::endl;
}
//通过返回的数据库句柄,建立记录急,你可以通过返回的这个句柄建立多个记录急
zlb_mysql::RecordSet rs(zlb.GetMysql());
rs.ExecuteSQL("select * from testtable");//这个语句大家都知道是什么意思了
cout<<rs.GetRecordCount()<<endl;
cout<<rs.GetFieldNum()<<endl;
cout<<rs[0].GetTabText()
<<endl;
for(int i=0;i<rs.GetRecordCount();++i)
{
for(int j=0;j<rs.GetFieldNum();++j)
cout<<rs[i][j];
cout<<endl;
}
zlb_mysql::Field *fd=rs.GetField();
cout<<fd->GetField_NO("Password")
<<endl;
cout<<rs[0]["Password"]<<endl;
cout<<rs[0][fd->GetField_NO("Password")]<<endl;
cout<<rs.GetFieldName(0)<<endl;
cout<<rs.GetFieldType("UserName")<<endl;
cout<<rs.GetCurrentPos()<<endl;
char s[50];
rs.GetCurrentFieldValue(1,s);
cout<<s<<endl;
cout<<rs.Move(1)<<endl;
cout<<rs.GetCurrentPos()<<endl;
rs.GetCurrentFieldValue(1,s);
cout<<s<<endl;
rs.MoveFirst();
while(!rs.IsEof())
{
rs.GetCurrentFieldValue("UserName",s);
cout<<s<<"\t";
rs.GetCurrentFieldValue("Password",s);
cout<<s<<"\t\n";
rs.MoveNext();
}
rs.GetFieldValue(0,"UserName",s);
cout<<s<<"\t";
rs.GetFieldValue(0,"Password",s);
cout<<s<<"\t\n";
}
以上所分享的是关于实例讲解如何使用C++操作MySQL数据库类,下面是编辑为你推荐的有价值的用户互动:
相关问题:如何在c/c++编程中使用数据库(sql server)?
答:操作 sql server 需要用到 ADO 驱动,这种驱动使用MFC做的包装类比较多一些,在控制台直接编写代码可能稍显繁琐。 可以参考 http://wenku.baidu.com/view/3995b8c8050876323112122d.html >>详细
相关问题:c++(或MFC)使用mysql数据库具体该掌握哪些东西,...
答:首先,应该熟悉基本的sql语句,至少包括数据库的创建,建表以及表的增、删、改、查。这是操作所有数据库的根本。 然后,因为具体的数据库有其自身的特性,你使用的是MySQL,那么你需要了解MySQL里面那些相应操作的具体语句。我的建议是,先安装... >>详细
相关问题:php如何使用类和数据库进行数据操作
答:用类? 打击 自己定义个不就行了! 用就$a = new XXX(); $a->doSql('select * from xx'); 就这么用啊! class XXX { mysql_connect("localhost", "root", "123456") or die("Could not connect: " . mysql_error()); mysql_query("SET character_... >>详细
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
