从db中选择记录并插入到C ++ map中

时间:2011-08-13 22:22:43

标签: c++

有人可以建议我一个很好的例子或链接来从MySQL中选择记录并将记录插入到地图中,这样我就可以用C ++进行分析。 我试图从数据库中提取价格数据,所以我有一个交易日期和销售价格。 我不想通过中间步骤将记录写入.csv文件。

THX!


我无法使用sql :: Connection,所以我使用了API。我试图从db中提取日期和销售额$,其他字段也是如此。所以,这是我的代码:

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

#include <vector>
#include <iterator>
#include <string>
#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;
}

但是我收到以下错误:

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

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

1 个答案:

答案 0 :(得分:4)

您需要使用C ++连接器。您可以从this link下载。

Here's the wiki page to get you started

编辑:我自己没有测试过,但是这样的事情应该有效:

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;