开发者

select records from db and insert into C++ map

Can someone suggest me a good example or link to select records from MySQL and insert the records into a map so I can do the analysis in C++. I am trying to pull in price data from the db, so I have a transaction date and sale price. I don't want to go through the intermediate step and write the records to a .csv file.

thx!


i was not able to get it work with sql::Connection so I used the API. I am trying to extract date and sales$'s from the db, which has other fields also. so, here is the code I have:

#include <iostream>
#include </usr/include/mysql/mysql.h>
#include </usr/include/sys/time.h> 
using namespace std;

#include <vector>
#include <iterator>
#include <string>开发者_StackOverflow社区
#include <map>

MYSQL *connection;
MYSQL mysql;
MYSQL_RES *resptr;
MYSQL_ROW row;
MYSQL_FIELD *field;

int query_state;

map<string, double> test;
string key;
double value;

int main() 
{
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,"localhost","userid","pwd","schema",0,0,0);

query_state = mysql_query(connection, "select pdate, sales from test;");

 resptr = mysql_store_result(connection); 


while ( ( row = mysql_fetch_row(resptr)) != NULL ) 
{

test[resptr->getString("pdate")]=resptr->getInt("sales"); 
} 

mysql_free_result(resptr);
mysql_close(connection);

return 0;
}

but I get the following error:

error: ‘struct MYSQL_RES’ has no member named ‘getString’

error: ‘struct MYSQL_RES’ has no member named ‘getInt’


You will need to use the C++ connector. You can download it from this link.

Here's the wiki page to get you started.

Edit: I haven't tested this myself, but something like this should work:

map<int, string> results;

sql::mysql::MySQL_Driver* driver = sql::mysql::get_mysql_driver_instance();
sql::Connection* con = driver->connect("tcp://127.0.0.1:3306", "user", "password");

sql::Statement* stmt = con->createStatement();
sql::ResultSet* res = stmt->executeQuery("SELECT id, label FROM test ORDER BY id ASC");
while (res->next())
{
    results[res->getInt("id")] = res->getString("label");
}

delete res;
delete stmt;
delete con;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜