mysql执行存储过程其实就是执行多条查询语句,存储过程是可编程的函数,在数据库中创建并保存,可以由SQL语句和控制结构组成。数据库中的存储过程可以看做是对编程中面向对象方法的模拟,它允许控制数据的访问方式。
static void
print_result(mysqlpp::StoreQueryResult& res, int index)
{
// Show how many rows are in result, if any
mysqlpp::StoreQueryResult::size_type num_results = res.size();
if (res && (num_results > 0)) {
cout << "Result set " << index << " has " << num_results <<
" row" << (num_results == 1 ? "" : "s") << ':' << endl;
}
//else {
//cout << "Result set " << index << " is empty." << endl;
//return;
//}
}
//执行查询语句会有多条返回结果(多行数据)
void ExecuteSql(const std::string& sSqlstring, std::list>& aRet)
{
try {
mysqlpp::Connection* pConnection = GetConnection();
mysqlpp::Query query = pConnection->query(sSqlstring);
mysqlpp::StoreQueryResult res = query.store();
query.reset();
if (res.size()>0)
{
size_t columns = res.num_fields();
mysqlpp::StoreQueryResult::iterator rit;
for (rit = res.begin(); rit != res.end(); ++rit)
{
std::map fieldVal;
for (unsigned int i = 0; i < columns; ++i)
{
fieldVal[res.field_name(i)] = (*rit)[i].c_str();
}
aRet.push_back(fieldVal);
}
}
}
catch (const mysqlpp::BadQuery& er) {
// Handle any query errors
cerr << "Query error: " << er.what() << endl;
return;
}
catch (const mysqlpp::BadConversion& er) {
// Handle bad conversions
cerr << "Conversion error: " << er.what() << endl <<
"\tretrieved data size: " << er.retrieved <<
", actual size: " << er.actual_size << endl;
return;
}
catch (const mysqlpp::Exception& er) {
// Catch-all for any other MySQL++ exceptions
cerr << "Error: " << er.what() << endl;
return;
}
}
static void
print_multiple_results(mysqlpp::Query& query)
{
// Execute query and print all result sets
mysqlpp::StoreQueryResult res = query.store();
print_result(res, 0);
for (int i = 1; query.more_results(); ++i) {
res = query.store_next();
print_result(res, i);
}
}
bool Execute_MultiStatement(std::vector& sContent)
{
try
{
mysqlpp::Connection* pConnection = GetConnection();
pConnection->set_option(new mysqlpp::MultiResultsOption(CLIENT_MULTI_STATEMENTS));
mysqlpp::Query query = pConnection->query();
for (auto content:sContent)
{
query << content << "\r ";
}
//cout << "Multi-query: " << endl << query << endl;
print_multiple_results(query);
query.reset();
}
catch (const mysqlpp::BadOption& err) {
std::cerr << err.what() << std::endl;
cerr << "This function requires MySQL 4.1.1 or later." << endl;
return false;
}
catch (const mysqlpp::ConnectionFailed& err) {
std::cerr << "Failed to connect to database server: " <<
err.what() << std::endl;
return false;
}
catch (const mysqlpp::Exception& er) {
// Catch-all for any other MySQL++ exceptions
std::cerr << "Error: " << er.what() << std::endl;
return false;
}
return true;
}