#include
"stdafx.h"
#include
"winsock.h"
#include
"mysql.h"
#pragma
comment
(
lib
,
"libmysql.lib"
)
#include
<iostream>
using
namespace
std
;
// SQL管理类
class
CMySqlManager
{
public
:
CMySqlManager
( );
~
CMySqlManager
( );
public
:
void
Prepare
( );
void
FetchAndStore
(
char
* );
void
ShowToEdit
( );
void
DisconnectSQL
( );
private
:
MYSQL
m_MySql
;
MYSQL_RES
*
m_pRes
;
MYSQL_ROW
m_Row
;
char
m_FlagOfConnect
;
// 连接成功与否标志 1 成功查询 0 为查询失败
char
m_FlagOfQuery
;
// 查询成功与否的标志 1 成功查询 0 为查询失败
};
CMySqlManager
::
CMySqlManager
( )
{
m_FlagOfConnect
= 0;
m_FlagOfQuery
= 0;
}
CMySqlManager
::~
CMySqlManager
( )
{
DisconnectSQL
( );
}
void
CMySqlManager
::
Prepare
( )
{
mysql_init
(&
m_MySql
);
if
(
m_FlagOfConnect
== 0)
{
// 连接Mysql服务器,本例使用本机作为服务器。
// 访问的数据库名称为“msyql”,参数中的user为你的登录用户名,***为登录密码,需要根据你的实际用户进行设置
if
(!
mysql_real_connect
(&
MySql
,
"localhost"
,
"root"
,
"1"
,
"gamedb3"
, 3306, 0, 0))
cout
<<
"mysql_real_connect failure!"
<<
endl
;
else
{
cout
<<
"Connect Successed!"
<<
endl
;
m_FlagOfConnect
= 1;
}
}
else
cout
<<
"Connected. Dupliacate Connect Fail "
<<
endl
;
}
void
CMySqlManager
::
FetchAndStore
(
char
*
SQL
)
{
if
(
m_FlagOfConnect
)
{
// 查询mysql数据库中的user表
if
(
mysql_query
(&
m_MySql
,
SQL
))
{
cout
<<
"mysql_real_query failure!"
<<
endl
;
m_FlagOfQuery
= 0;
return
;
}
// 存储结果集
m_pRes
=
mysql_store_result
(&
m_MySql
);
if
(
NULL
==
res
)
{
cout
<<
"mysql_store_result failure!"
<<
endl
;
m_FlagOfQuery
= 0;
}
else
{
m_FlagOfQuery
= 1;
cout
<<
"Query Succeed! "
<<
endl
;
}
}
else
cout
<<
"Fail To Quey "
<<
endl
<<
" Connected Fail "
<<
endl
;
}
void
CMySqlManager
::
ShowToEdit
( )
{
if
(
m_FlagOfQuery
== 1)
{
cout
<<
"Load Data ...... "
<<
endl
<<
endl
;
int
j
= 0;
j
=
mysql_num_fields
(
m_pRes
);
// 获取每条记录的字段数
while
(
row
=
mysql_fetch_row
(
m_pRes
))
{
for
(
int
k
= 0;
k
<
j
;
k
++)
cout
<<
row
[
k
]<<
" "
;
cout
<<
endl
<<
endl
;
}
mysql_free_result
(
m_pRes
);
}
else
cout
<<
" Fetch Failed!"
<<
endl
;
}
void
CMySqlManager
::
DisconnectSQL
( )
{
mysql_close
(&
m_MySql
);
m_FlagOfConnect
= 0;
m_FlagOfQuery
= 0;
cout
<<
"DisConnected!"
<<
endl
;
}
int
_tmain
(
int
argc
,
_TCHAR
*
argv
[])
{
CMySqlManager
MySql
;
MySql
.
Prepare
( );
MySql
.
FetchAndStore
(
"select id,name,mate from cq_user where id=500001 "
);
MySql
.
ShowToEdit
( );
MySql
.
FetchAndStore
(
"select id,name,mate from cq_user where id=500002 "
);
MySql
.
ShowToEdit
( );
MySql
.
DisconnectSQL
( );
getchar
( );
return
0;
}