实例讲解如何使用C++ *** 作MySQL数据库类

实例讲解如何使用C++ *** 作MySQL数据库类,第1张

/ project: 通用模块 ( 用 c++ 处理 mysql 数据库类,像ADO ) description: 通过DataBase,RecordSet,Record,Field类,实现对mysql数据库的 *** 作 包括连接、修改、添加、删除、查询等等,像ADO一样 *** 作数据库,使 用方便 ( the end of this file have one sample, welcom to use ) file:zlb_mysqlh author: @ zlb time:2005-12-12 --/ #ifndef ZLB_MYSQL_H #define ZLB_MYSQL_H #include "mysqlh" #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); }; / 1 单条记录 2 [int ] *** 作 [""] *** 作 / class Record { public: / 结果集 / vector<string> m_rs; / 字段信息 占用4字节的内存 当记录数很大是回产生性能问题 / Field m_field; public : Record(){}; Record(Field m_f); ~Record(); void SetData(string value); / [""] *** 作 / string operator[](string s); string operator[](int num); / null值判断 / bool IsNull(int num); bool IsNull(string s); / 用 value tab value 的形式 返回结果 / string GetTabText(); }; / 1 记录集合 2 [int ] *** 作 [""] *** 作 3 表结构 *** 作 4 数据的插入修改 / 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); }; / 1 负责数据库的连接关闭 2 执行sql 语句(不返回结果) 3 处理事务 / class DataBase { public : DataBase(); ~DataBase(); private : / msyql 连接句柄 / 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); / 测试mysql服务器是否存活 / int Ping(); / 关闭mysql 服务器 / int ShutDown(); / 主要功能:重新启动mysql 服务器 / int ReBoot(); / 说明:事务支持InnoDB or BDB表类型 / / 主要功能:开始事务 / 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 / project: 通用模块 ( 用 c++ 处理 mysql 数据库类,像ADO ) description: 通过DataBase,RecordSet,Record,Field类,实现对mysql数据库的 *** 作 包括连接、修改、添加、删除、查询等等,像ADO一样 *** 作数据库,使 用方便 ( the end of this file have one sample, welcom to use ) file:zlb_mysqlcpp author: @ zlb time:2005-12-12 --/ #include "stdafxh" #include "zlb_mysqlh" 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_namesize ();i++) { if(!m_name[i]compare (field_name)) return i; } return -1; } /-----------------------------------------------------/ / +++++++++++++++++++++++++++++++++++++++++++++++++++ / / 1 单条记录 2 [int ] *** 作 [""] *** 作 / Record::Record(Field m_f) { m_field =m_f; } Record::~Record(){}; void Record::SetData(string value) { m_rspush_back (value); } / [""] *** 作 / string Record::operator[](string s) { return m_rs[m_field->GetField_NO(s)]; } string Record::operator[](int num) { return m_rs[num]; } / null值判断 / 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; } / 主要-功能:用 value tab value 的形式 返回结果 / string Record::GetTabText() { string temp; for(unsigned int i=0 ;i<m_rssize();i++) { temp+=m_rs[i]; if(i<m_rssize ()-1) temp+="\t"; } return temp; } /-----------------------------------------------------/ / +++++++++++++++++++++++++++++++++++++++++++++++++++ / / 1 记录集合 2 [int ] *** 作 [""] *** 作 3 表结构 *** 作 4 数据的插入修改 / RecordSet::RecordSet() { res = NULL; row = NULL; pos = 0; } RecordSet::RecordSet(MYSQL hSQL) { res = NULL; row = NULL; m_Data = hSQL; pos = 0; } RecordSet::~RecordSet() { } / 处理返回多行的查询,返回影响的行数 成功返回行数,失败返回-1 / 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_fieldm_namepush_back(fd->name); m_fieldm_typepush_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]))) { tempSetData (""); } else { tempSetData(row[k]); } } //添加新记录 m_spush_back (temp); } mysql_free_result(res ) ; return m_ssize(); } 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_ssize()) { pos = m_ssize()-1; return pos; }else { pos = l; return pos; } } } / 移动游标到开始位置 / bool RecordSet::MoveFirst() { pos = 0; return true; } / 移动游标到结束位置 / bool RecordSet::MoveLast() { pos = m_ssize()-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_ssize())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_fieldm_nameat(iNum)c_str(); } / 返回字段类型 / const int RecordSet::GetFieldType(char sName) { int i = m_fieldGetField_NO(sName); return m_fieldm_typeat(i); } const int RecordSet::GetFieldType(int iNum) { return m_fieldm_typeat(iNum); } / 返回指定序号的记录 / Record RecordSet::operator[](int num) { return m_s[num]; } / -------------------------------------------------- / / +++++++++++++++++++++++++++++++++++++++++++++++++++ / / 1 负责数据库的连接关闭 2 执行sql 语句(不返回结果) 3 处理事务 / DataBase::DataBase() { m_Data = NULL; } DataBase::~DataBase() { if(NULL != m_Data) { DisConnect(); } } / 返回句柄 / MYSQL DataBase::GetMysql() { return m_Data; } / 主要功能:连接数据库 参数说明: 1 host 主机ip地址或者时主机名称 2 user 用户名 3 passwd 密码 4 db 欲连接的数据库名称 5 port 端口号 6 uinx 嵌套字 7 client_flag 客户连接参数 返回值: 0成功 -1 失败 / 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, hostc_str(), userc_str(), passwdc_str(), dbc_str(),port , NULL, client_flag)) { //选择制定的数据库失败 if ( mysql_select_db( m_Data, dbc_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) ; } / 主要功能: 执行非返回结果查询 参数:sql 待执行的查询语句 返回值; n为成功 表示受到影响的行数 -1 为执行失败 / int DataBase::ExecQuery(string sql) { if(!mysql_real_query(m_Data,sqlc_str (),(unsigned long)sqllength()) ) { //得到受影响的行数 return (int)mysql_affected_rows(m_Data) ; } else { //执行查询失败 return -1; } } / 主要功能:测试mysql服务器是否存活 返回值:0 表示成功 -1 失败 / int DataBase::Ping() { if(!mysql_ping(m_Data)) return 0; else return -1; } / 主要功能:关闭mysql 服务器 返回值;0成功 -1 失败 / int DataBase::ShutDown() { if(!mysql_shutdown(m_Data,SHUTDOWN_DEFAULT)) return 0; else return -1; } / 主要功能:重新启动mysql 服务器 返回值;0表示成功 -1 表示失败 / int DataBase::ReBoot() { if(!mysql_reload(m_Data)) return 0; else return -1; } / 说明:事务支持InnoDB or BDB表类型 / / 主要功能:开始事务 / int DataBase::Start_Transaction() { if(!mysql_real_query(m_Data, "START TRANSACTION" , (unsigned long)strlen("START TRANSACTION") )) { return 0; } else //执行查询失败 return -1; } / 主要功能:提交事务 返回值:0 表示成功 -1 表示失败 / int DataBase::Commit() { if(!mysql_real_query( m_Data, "COMMIT", (unsigned long)strlen("COMMIT") ) ) { return 0; } else //执行查询失败 return -1; } / 主要功能:回滚事务 返回值:0 表示成功 -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, sqlc_str(),(unsigned long)sqllength())) { //保存查询结果 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()"); } / 主要功能:建立新数据库 参数:name 为新数据库的名称 返回:0成功 -1 失败 / int DataBase::Create_db(string name) { string temp ; temp="CREATE DATABASE "; temp+=name; if(!mysql_real_query( m_Data,tempc_str () , (unsigned long)templength ()) ) return 0; else //执行查询失败 return -1; } / 主要功能:删除制定的数据库 参数:name 为欲删除数据库的名称 返回:0成功 -1 失败 / int DataBase::Drop_db(string name) { string temp ; temp="DROP DATABASE "; temp+=name; if(!mysql_real_query( m_Data,tempc_str () , (unsigned long)templength ()) ) return 0; else //执行查询失败 return -1; } /-----------------------------------------------------/ }; / 使用例子 / #include "zlb_mysqlh" using namespace std; void main() { zlb_mysql::DataBase zlb; //连接数据库 if(-1 == zlbConnect("localhost"/本地数据库,可以是远程 ip/, "root"/用户名/,"apple"/密码/, "test"/数据库名/, 0,0/两个标志,mysql文档有说明,一般为0/)) { std::cout<<"connect failed "<<std::endl; } else { std::cout<<"connect success"<<std::endl; } //通过返回的数据库句柄,建立记录急,你可以通过返回的这个句柄建立多个记录急 zlb_mysql::RecordSet rs(zlbGetMysql()); rsExecuteSQL("select from testtable");//这个语句大家都知道是什么意思了 cout<<rsGetRecordCount()/返回的总的记录数/<<endl; cout<<rsGetFieldNum()/返回的总的字段数/<<endl; cout<<rs[0]GetTabText()/返回第一条记录,你也可以rs[1]GetTabText() 如果你有多条记录, / <<endl; /实现遍列,也可以使用后面的遍列方式/ for(int i=0;i<rsGetRecordCount();++i) { for(int j =0;j<rsGetFieldNum();++j) cout<<rs[i][j]; cout<<endl; } zlb_mysql::Field fd = rsGetField();/你可以通过这样的方式,获取字段的信息/ cout<<fd->GetField_NO("Password")/返回我表里的 Password 字段的位置,不 是记录的位置/ <<endl; cout<<rs[0]["Password"]<<endl;/输出第0行第Password列的值/ cout<<rs[0][fd->GetField_NO("Password")]<<endl;/你也可以这样/ cout<<rsGetFieldName(0)/获取字段的名字/<<endl; cout<<rsGetFieldType("UserName")/获取字段的类型,是mysql里定义的/<<endl; cout<<rsGetCurrentPos()/获取当前记录的位置/<<endl; char s[50]; rsGetCurrentFieldValue(1,s);/获取当前记录对应字段的值/ cout<<s<<endl; cout<<rsMove(1)<<endl;/移动游标,正数往前 负数往后/ cout<<rsGetCurrentPos()<<endl; rsGetCurrentFieldValue(1,s); cout<<s<<endl; rsMoveFirst();/移动游标到最前/ while(!rsIsEof()/判断是否到达游标尾,实现遍列/) { rsGetCurrentFieldValue("UserName",s); cout<<s<<"\t"; rsGetCurrentFieldValue("Password",s); cout<<s<<"\t
"; rsMoveNext(); } rsGetFieldValue(0,"UserName",s);/获取指定行 的记录值/ cout<<s<<"\t"; rsGetFieldValue(0,"Password",s); cout<<s<<"\t
"; }

在以前不论是使用SQLyog MySQL GUI或是phpMyAdmin访问数据库,第一步一定是输入访问数据库的账号与密码,当然Dreamweaver也不例外。在Dreamweaver中,我们通过建立 MySQL联机告诉Dreamweaver连接的MySQL数据库地址、名称,以及访问的账号和密码。
在一个网站中,我们只需对一个数据库建立一次MySQL连接。通常网络上的主机空间也只支持访问一个数据库。例如虚拟主机,最基本的方案是搭配1个MySQL数据库。
在文件面板中打开indexphp,接着选择应用程序→数据库面板,单击+按钮后选择MySQL连接。

建立MYSQL连接
在建立数据库连接前,我们必须设置好图6-5中的前面3个选项,如果依照书中叙述设置好,那么基本上便不会有问题。当然必须至少打开一个网页,否则会有无法选择的情况发生。

未打开页面,选项均无法选择
d出如图6-7所示的窗口,请依照其下面的说明进行设置。可以单击测试按钮测试是否有问题,单击确定按钮后就可以在应用程序→数据库面板中看到所建立的数据库连接。我们可以 *** 作这个树状结构(见图6-8)检查连接的数据库、数据表与字段名称及属性等。也可以打开phpMyAdmin来检查数据库结构,并与面板内的信息对比。字段与功能说明。

建立连接
数据库内的数据表、字段和属性
字段与功能说明
字 段

说 明
连接名称

依个人喜好自由输入
MySQL服务器

MySQL服务器的位置,一般设置为localhost,除非所要存取的MySQL数据库不在网页所在的主机上,而且该MySQL数据库也提供对外的连接
用户名

访问MySQL数据库的用户名称
密码

访问MySQL数据库的用户密码
数据库

选择所要建立连接的数据库名称,可以单击选取按钮浏览MySQL服务器上的所有数据库。我们选择刚导入的范例数据库database
在建立完成MySQL连接后,在文件面板中会看到Dreamwaver自动建立了Connections文件夹,在该文件夹下有一个与前面所建立的MySQL连接名称相同的文件。
Connections文件夹
Connections文件夹是Dreamweaver用来存放MySQL连接设置文件的文件夹。
打开该文件并使用代码视图,可以看到有关连接数据库的设置。

数据库连接设置
在这个文件中定义了与MySQL服务器的连接(mysql_pconnect函数),包括以下内容。
$hostname:MySQL服务器的地址。
$database:连接数据库的名称。
$username:用户名称。
$password:用户密码。
定义的值与我们前面在图形界面所设置的值是对应的,然后利用函数mysql_pconnect与数据库连接。连接后才能对数据库进行查询、新增、修改或删除的 *** 作。
如果在网站制作完成后将文件上传至网络上的主机空间时发现,网络上的MySQL服务器访问的用户名、密码等方面与本机设置有所不同,可以直接修改位于Connection文件夹下的db_connphp文件。但还是建议直接在本机配合网络主机上的环境来设置。例如,你拥有虚拟主机所提供的MySQL数据库名称为xu354jp6,但在本机却要命名为Charles,虽然可能会好看些,但到时候就会多一个麻烦了。
对于如何将本机已经完成的网站移植到网络上的空间,将在附录中有详细的介绍。
总之,在建立好数据库连接后,除非要连接MySQL数据库里的另一个数据库,否则不需要再做这个步骤了。

1、在MySQL数据库安装时选择过MySQL服务器随系统启动,但如果没有选择,也没关系,可以在可以在Windows服务管理器启动,具体在开始菜单搜索servicesmsc,

2、单击出现如下图窗口,下滑鼠标找到MySQL57:

3、右击后点击启动,MySQL57旁边状态列显示“已启动”字样,说明启动成功。如下图:

二、 登录MySQL数据库

4、 用系统命令行工具登录,点击开始菜单,找到附件,点击命令提示符。

5、在命令行中输入cd加空格然后粘贴bin路径:cd c:\Program Files (x86)\MySQL\MySQL Server 57\bin 回车命令行定位到c:\Program Files (x86)\MySQL\MySQL Server 57\bin>,在后面输入mysql –h localhost –u root –p(这些都是安装时设置好的)敲回车,

6、出现Enter password:在后面输入安装时设置的登录密码,按回车后出现Welcome to the MySQL monitor说明登陆成功。如下图:

7、用安装时配置好的命令行工具登录,在开始菜单,点击MySQL 57 Command Line Client 或下面搜索程序框中输入comm选择MySQL 57 Command Line Client启动DOS命令窗口。如下图:

8、在窗口Enter password:处输入安装时设置的MySQL数据库客户端登陆密码,回车,如果出现Welcom to the MySQL monitor等字眼表示登陆服务器成功,可以在闪烁光标处输入SQL可执行语言:如下图:


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/12784271.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-28
下一篇 2023-05-28

发表评论

登录后才能评论

评论列表(0条)

保存