私はstd::string
の内部でバイナリデータを使用して柔軟なソリューションを考え出しました。
現在の回答が古い(2013)ため、私はpqxx 5.0.1を使用して複数の挿入クエリを探していたので、この新しいソリューションを提案します。
以下の解決策を使用すると、for loop
を使用して1つの挿入クエリで複数のバイナリデータを追加する柔軟性が得られます。
CustomStruct data = .... ; // have some binary data
// initialise connection and declare worker
pqxx::connection conn = new pqxx::connection(...);
pqxx::work w(conn);
// prepare query
string query += "INSERT INTO table (bytea_field) VALUES ("
// convert your data in a binary string.
pqxx::binarystring blob((void *)&(data), data.size());
// avoid null character to bug your query string.
query += "'"+w.esc_raw(blob.str())+"');";
//execute query
pqxx::result rows = w.exec(query);
私たちは、あなたのデータ型(たとえばCustomStruct
)の範囲を持っている必要があり、あなたの好みのバイナリ形式でそれをバックキャストすることができるはずデータベースからデータを取得したいです。
// assuming worker and connection are declared and initialized.
string query = "SELECT bytea_field FROM table;";
pqxx::result rows = w.exec(query);
for(pqxx::result::iterator col = rows.begin(); col != rows.end(); ++col)
{
pqxx::binarystring blob(col[0]);
CustomStruct *data = (CustomStruct*) blob.data();
...
}
これはpqxx 5.0.1
、c++11
とpostgresSQL 9.5.8
出典
2017-08-30 22:52:47
LAL
私はあなたのソリューションを好きでテストされましたが、私はconn.prepareを使用して好きではありません。 1つのクエリ(パフォーマンスの問題)で挿入する 'n'要素があるときは、私の制限です。私は解決策(pqxx 5.0.1)に取り組んでいます。 – LAL