//获取更新数据的sql语句 where语句中用户要包含where 更新
std::string GetUpdatesql(XDATA kv, std::string table, std::string where);
std::string LXMysql::GetUpdatesql(XDATA kv, std::string table, std::string where)
{
string sql = "";
if (kv.empty() || table.empty())
{
return "";
}
//update t_vedio set name= 'update001', size=1000 where id =10;
sql = "update `";
sql += table;
sql += "` set ";
for (auto ptr = kv.begin(); ptr != kv.end();ptr++)
{
sql += "`";
sql += ptr->first;
sql += "`=' ";
sql += ptr->second.data;
sql += "',";
}
//去除多余的逗号
sql[sql.size() - 1] = ' ';
sql += " ";
sql += where;
return sql;
}
//返回更新数量,失败返回-1
int Update(XDATA kv, std::string table, std::string where);
int LXMysql::Update(XDATA kv, std::string table, std::string where)
{
if (!mysql)
{
return -1;
}
string sql = GetUpdatesql(kv, table, where);
if (sql.empty())
{
return -1;
}
if (!Query(sql.c_str()))
{
return -1;
}
return mysql_affected_rows(mysql);
}
3、测试
//更新数据
? ? //修改id=2的数据
? ? XDATA udata;
? ? udata["name"] = "update002";
? ? cout << " my.Update=" << my.Update(udata, "t_vedio", "where id=2") << endl;
?