2017-08-25 49 views
0

我問了關於stackexchange db admin的同樣的問題,這似乎是問題的適當位置,但問題是沒有人甚至認爲這個問題。所以我在這裏再次發佈相同的問題:MySQL C++連接器:使用SetBlob()在查詢中設置多個blob數據的正確方法是什麼?

我正在處理Mysql表格插入。該表創建語句是這樣的:

CREATE TABLE files_table (fid INT NOT NULL AUTO_INCREMENT, idx TINYBLOB, head TINYBLOB, size BLOB, PRIMARY KEY(fid)); 

我可以插入記錄手動

mysql> select * from files_table order by fid asc; 
+-----+------+------+------------+ 
| fid | idx | head | size  | 
+-----+------+------+------------+ 
| 1 | 1 | 1 | 1   | 
+-----+------+------+------------+ 

但是當我使用的連接器使用C++連接器添加下一個值:

class StreamBufferData : public std::streambuf 
{ 
public: 
    StreamBufferData(const char *in_data, size_t in_size) 
    { 
     setg(in_data, in_data, in_data + in_size); 
    } 
}; 

enum{QUERY_SIZE=256;} 
char ins[QUERY_SIZE]; 

strcpy(ins, "INSERT INTO files_table (idx, head, size) VALUES (?,?,?)"); 

try 
{ 
    std::unique_ptr<sql::PreparedStatement> statement(ptr_connection->prepareStatement(ins)); 

    char test_data[2] = "0"; 
    StreamBufferData buffer0(test_data, 2); 
    std::istream test_s0(&buffer0); 
    statement->setBlob(1, &test_s0); 

    strcpy(test_data, "1"); 
    StreamBufferData buffer1(test_data, 2); 
    std::istream test_s1(&buffer1); 
    statement->setBlob(2, &test_s1); 

    strcpy(test_data, "2"); 
    StreamBufferData buffer2(test_data, 2); 
    std::istream test_s2(&buffer2); 
    statement->setBlob(3, &test_s2); 

    statement->executeUpdate(); 
} 
catch(sql::SQLException &e) 
{ 
    std::cout << e.what() << ‘\n’; 
    return; 
} 

的結果是:

+-----+------+------+------------+ 
| fid | idx | head | size  | 
+-----+------+------+------------+ 
| 1 | 1 | 1 | 1   | 
| 2 | 2 | 2 | 2   | 
+-----+------+------+------------+ 

只有最後一個值被正確插入到表格中。我的問題是:用戶msql :: PreparedStatement :: setBlob()在查詢中設置多個blob的正確方法是什麼?

[環境]
的Ubuntu 16.04.2
的MySQL 5.7
的MySQL連接器版本:7.1.1.7
升壓1.58.0
G ++ 5.4.0

感謝您的幫助

回答

0

不同std::istream對象指向由test_data分配的相同緩衝區。我以爲istream對象會複製char數組中的值。事實是,事實並非如此。

它還值得指出,如果std :: istream對象在執行statement-> executeUpdate()之前被銷燬。最後一個流對象將被填充到表的第一列,這可能是我的機器上未定義的行爲(Ubuntu 16.04.2 LTS)。它看起來像:

+-----+------+------+------------+ 
| fid | idx | head | size  | 
+-----+------+------+------------+ 
| 1 | 1 | 1 | 1   | 
| 2 | 2 |  |   | 
+-----+------+------+------------+ 

所以,如果表中有奇怪的結果像以前的表,檢查代碼,以確保標準::流時,StreamBufferData並指向緩衝區指針仍然有效,直到聲明 - >執行executeUpdate()。

相關問題