mysql執(zhí)行存儲(chǔ)過程其實(shí)就是執(zhí)行多條查詢語句,存儲(chǔ)過程是可編程的函數(shù),在數(shù)據(jù)庫中創(chuàng)建并保存,可以由SQL語句和控制結(jié)構(gòu)組成。數(shù)據(jù)庫中的存儲(chǔ)過程可以看做是對(duì)編程中面向?qū)ο蠓椒ǖ哪M,它允許控制數(shù)據(jù)的訪問方式。
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;
//}
}
//執(zhí)行查詢語句會(huì)有多條返回結(jié)果(多行數(shù)據(jù))
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;
}