Download MySQL++ User Manual

Transcript
MySQL++ User Manual
order to simplify editing. Also, all of these examples have full error checking code, showing off the power of
MySQL++'s exception handling features.
Loading binary file in a BLOB column
Since MySQL 3.23, BLOB columns have been available, but their use is sometimes not straightforward. Besides
showing how easy it can be with MySQL++, this example demonstrates several features of MySQL++. The program
requires one command line parameter, which is a full path to the binary file. This is examples/load_file.cpp:
#include <mysql++.h>
#include <sys/stat.h>
#include <fstream>
#include <stdlib.h>
using namespace std;
using namespace mysqlpp;
const
const
const
const
const
const
char
char
char
char
char
char
MY_DATABASE[] = "telcent";
MY_TABLE[] = "fax";
MY_HOST[] = "localhost";
MY_USER[] = "root";
MY_PASSWORD[] = "";
MY_FIELD[] = "fax"; // BLOB field
int
main(int argc, char *argv[])
{
if (argc < 2) {
cerr << "Usage : load_file full_file_path" << endl << endl;
return -1;
}
Connection con(use_exceptions);
try {
con.connect(MY_DATABASE, MY_HOST, MY_USER, MY_PASSWORD);
Query query = con.query();
ostringstream strbuf;
ifstream In(argv[1], ios::in | ios::binary);
struct stat for_len;
if ((In.rdbuf())->is_open()) {
if (stat(argv[1], &for_len) == -1)
return -1;
unsigned int blen = for_len.st_size;
if (!blen)
return -1;
char *read_buffer = new char[blen];
In.read(read_buffer, blen);
string fill(read_buffer, blen);
strbuf << "INSERT INTO " << MY_TABLE << " (" << MY_FIELD <<
") VALUES(\"" << mysqlpp::escape << fill << "\")" << ends;
query.exec(strbuf.str());
delete[]read_buffer;
}
else
cerr << "Failed to open " << argv[1] <<
'.' << endl;
}
catch (const BadQuery& er) {
// Handle any query errors
cerr << "Query error: " << er.what() << endl;
return -1;
}
catch (const BadConversion& er) {
// Handle bad conversions
cerr << "Conversion error: " << er.what() << endl <<
21