我已經開始用C++ libcql
庫卡珊德拉的工作..我想用C++與libcql庫從卡桑德拉檢索數據..如何將結果存儲在C++中的Map中,然後迭代它並打印出結果?
每當我去使用cqlsh
在命令行上和不選擇這樣的 -
select record_name, record_value from profile_user where user_id = '1';
我總是在cql命令行上得到以下輸出,其中record_name
和record_value實際上是TEXT datatype which is UTF-8 encoded string
的列。
record_name | record_value
-------------+--------------
e1 | hello
e2 | hello
現在來到C++世界 -
現在我試圖從C++ libcql library
獲取同樣的事情...我將運行在以上C++選擇查詢相同,我想返回一個將有e1, e2 as the key
和HELLO as there value inside that map
的地圖...有可能在C++中做到這一點?
/**
* This method will retrieve the data from Cassandra..
* And then call print_rows method to print it out on the console
*/
void get_attributes(string id){
try{
// some code
//Connection open
connection_open();
execute_query("USE testks;");
//this will give me the result back of the select query
cql_result_t& result = execute_query("select * from profile_user where key ='"+id+"';");
// and this is printing it out on the console
print_rows(result);
// some code
} catch (int e){
// some code here
}
}
下面是這將運行我的C++程序後,打印出來的控制檯對結果的方法 -
/**
* This method prints out the result on the console.. *
*
*/
void print_rows(cql::cql_result_t& result) {
while (result.next()) {
for (size_t i = 0; i < result.column_count(); ++i) {
cql::cql_byte_t* data = NULL;
cql::cql_int_t size = 0;
result.get_data(i, &data, size);
std::cout.write(reinterpret_cast<char*>(data), size);
std::cout << " | ";
}
std::cout << std::endl;
}
}
,我在控制檯上看到運行我的C以上後,結果++程序是一樣的東西這 -
e1 | hello |
e2 | hello |
但是我期待的是 - 。結果存儲在C++中的地圖,以這樣的方式使得鍵應該是e1 and e2
在地圖中。並且它們的值應該是HELLO
在同一個Map中...然後迭代Map並在C++中輸出結果?這可能與我現有的代碼有關嗎?
如果是的話,任何人都可以提供一個簡單的例子嗎?謝謝...
它基本上是一個C++的問題,我猜..只是檢索數據,並把它放到地圖......但我面臨的問題是我的背景是完全在Java中,所以有點困難的時候弄清楚如何做到這一點...
我稍微改變了我的表的設計在這個問題上我原來的問題here,而不是使用集合,我現在使用組合鍵..
但如果我能找出我以前的問題的解決方案,然後我將採用這種方法,否則我將採用這種方法..
感謝您的幫助......
更新代碼: -
隨着下面的變化,它總是打印出第一個結果兩次?不知道爲什麼?
void print_rows(cql::cql_result_t& result){
while (result.next()) {
for (size_t i = 0; i < result.column_count(); ++i) {
cql::cql_byte_t* data = NULL;
cql::cql_int_t size = 0;
result.get_data(i, &data, size);
// std::cout.write(reinterpret_cast<char*>(data), size);
// std::cout << " | ";
if(!flag) {
key = reinterpret_cast<char*>(data);
flag = true;
} else if(flag) {
value = reinterpret_cast<char*>(data);
m[key] = value;
flag = false;
}
}
std:map<std::string, std::string>::const_iterator it = m.begin();
for (;it!=m.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
std::cout << std::endl;
}
}
e1 : hello
e1 : hello
e2 : hello
我在這裏做什麼錯了?
我唯一的問題是如何將print_rows的結果放入std :: map或無序映射(無論哪一個是高效的),然後迭代它並打印出結果。 – ferhan
可能的重複[將結果存儲在C++中的Map中,然後迭代它然後打印出來?](http://stackoverflow.com/questions/19341994/store-the-result-in-a-map-in- c-then-then-iterate-it-and-then-print-out) – Raedwald