gpt4 book ai didi

c++ - 从数据库中选择记录并插入到 C++ 映射中

转载 作者:行者123 更新时间:2023-11-30 02:08:18 27 4
gpt4 key购买 nike

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

谢谢!


我无法让它与 sql::Connection 一起工作,所以我使用了 API。我正在尝试从数据库中提取日期和 sales$,它也有其他字段。所以,这是我的代码:

#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’

最佳答案

您将需要使用 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;

关于c++ - 从数据库中选择记录并插入到 C++ 映射中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7053680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com