linux对mysql使用,linux下使用c++语言对mysql数据库操作

#include "DBAccess.h"

#include

//using namespace std;

DBAccess::DBAccess()

{

}

DBAccess::~DBAccess()

{

}

bool DBAccess::MysqlConnect()

{

mysql_init(&mysql);

if(mysql_real_connect(&mysql,"localhost","root","123456","DBTroFish",3306,NULL,0))//参数:主机localhost,用户名root,密码root,数据库DBTroFish

{

return true;

}

else

{

return false;

}

}

bool DBAccess::ExecuteSQL(std::string sql)//对数据的增删改操作

{

if(!MysqlConnect())

{

cout<

mysql_close(&mysql);//有效解决too many connection

return false;

//exit(1);//整个程序退出

}

if(mysql_query(&mysql,sql.c_str()))//返回值:0表示正常,非0表示发生了错误

{

cout<

mysql_close(&mysql);

return false;

}

if(mysql_affected_rows(&mysql)>0)//返回值:>0表示影响的行数,=0表示无结果,=-1表示错误

{

mysql_close(&mysql);

return true;

}

else

{

mysql_close(&mysql);

return false;

}

}

MYSQL_RES* DBAccess::GetDataSet(std::string sql)//多行数据查询操作

{

MysqlConnect();

if(mysql_query(&mysql,sql.c_str()))

{

cout<

}

result=mysql_store_result(&mysql);

mysql_close(&mysql);

//mysql_free_result(result);//要在使用后才调用此方法,不然内存会不断增长直至程序结束

return result;

}

MYSQL_ROW DBAccess::GetRow(std::string sql)//单行数据查询操作

{

result=GetDataSet(sql);

if(mysql_num_rows(result))

{

row=mysql_fetch_row(result);

mysql_free_result(result);//解决内存不断增长问题

return row;

}

else

{

return NULL;

}

}

string DBAccess::IntToString(int a)

{

char t[20];

sprintf(t,"%d",a);

return t;

}

#include

#include

#include

#include

#include

#include "DBAccess.h"

#include

using namespace std;

int main()

{

if (1)

{

DBAccess myDBAccess;

string sql;

sql

= "insert into tblCoinDetail(CoinTime,Bet,BeginCredit,dEndCredit,GiftFlag)values('2011-02-42 1:1:1','1',5041,115,1)";

if (myDBAccess.ExecuteSQL(sql))

cout << "操作成功" << endl;

else

cout << "操作失败" << endl;

}

else

{

DBAccess myDBAccess;

MYSQL_ROW row;

string

sql =

"select date(CoinTime),sum(BeginCredit),sum(EndCredit),sum(BeginCredit-EndCredit) from tblCoinDetail group by CoinTime";

MYSQL_RES *result;

result = myDBAccess.GetDataSet(sql);

if(result!=NULL)// if (mysql_num_rows(result))//判断是否为空

{

while ((row = mysql_fetch_row(result)))

{

if(row[0]==NULL)//解决空地址问题

{

row[0]=(char*)"2011-01-01";

}

if(row[2]==NULL)

{

row[2]=(char*)"0";

}

fprintf(stdout, "%s|/t%s|/t%s|/t%s/n", row[0], row[1],row[2], row[3]);

}

}    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值