Download MySQL++ User Manual

Transcript
MySQL++ User Manual
The quote manipulator both quotes strings, and escapes any characters that are special in SQL.
3.7. Specialized SQL Structures
Retrieving data
The next example introduces one of the most powerful features of MySQL++: Specialized SQL Structures (SSQLS).
This is examples/custom1.cpp:
#include "util.h"
#include <mysql++.h>
#include <custom.h>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
// The following is calling a very complex macro which will create
// "struct stock", which has the member variables:
//
//
string item
//
...
//
Date sdate
//
// plus methods to help populate the class from a MySQL row
// among other things that I'll get to in a later example.
sql_create_5(stock,
1, 5,
// explained in the user manual
string, item,
mysqlpp::longlong, num,
double, weight,
double, price,
mysqlpp::Date, sdate)
int
main(int argc, char *argv[])
{
// Wrap all MySQL++ interactions in one big try block, so any
// errors are handled gracefully.
try {
// Establish the connection to the database server.
mysqlpp::Connection con(mysqlpp::use_exceptions);
if (!connect_to_db(argc, argv, con)) {
return 1;
}
// Retrieve the entire contents of the stock table, and store
// the data in a vector of 'stock' SSQLS structures.
mysqlpp::Query query = con.query();
query << "select * from stock";
vector<stock> res;
query.storein(res);
// Display the result set
print_stock_header(res.size());
vector<stock>::iterator it;
for (it = res.begin(); it != res.end(); ++it) {
print_stock_row(it->item, it->num, it->weight, it->price,
it->sdate);
}
}
catch (const mysqlpp::BadQuery& er) {
// Handle any query errors
cerr << "Query error: " << er.what() << endl;
return -1;
12