在C++中的Sybase表上运行SQL命令

Running SQL Commands on Sybase Table in C++

本文关键字:运行 SQL 命令 C++ 中的 Sybase      更新时间:2023-10-16

用屏幕截图中的修改代码更新

有一个Sybase数据库设置,提供的isql脚本可以连接到它。我现在要做的是能够连接到数据库,在数据库上运行一些sql命令(无论是否使用isql脚本),并将输出存储在数据结构中,以便在c++中处理每一行。我在网上发现了一小段代码,它应该允许我通过将命令作为c样式字符串传入来运行isql脚本,但试图编译cpp文件时会出现未在范围中声明的popen和pclose错误。如果有其他连接数据库的方法,或者如果您知道如何解决该错误,请告诉我。

原始代码:

#include <stdio.h>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
std::string exec(const char* cmd) {
  char buffer[128];
  std::string result = "";
  std::shared_ptr<FILE> pipe( popen(cmd, "r"), pclose());
  if (!pipe) throw std::runtime_error("popen() failed!");
  while (!feof(pipe.get())) {
    if (fgets(buffer, 128, pipe.get()) != NULL)
      result += buffer;
  }
  return result;
}

使用GNU++14编译代码以响应ildjarn

使用lambda函数为管道编译代码以响应max66

是否在作用域中声明?

你确定吗?

我的编译器说pclose()需要一个参数。

我建议您使用自定义deleter修改pipe声明;一个简单的lambda函数应该可以工作;类似的东西

std::shared_ptr<FILE> pipe( popen(cmd, "r"), [](auto ptr) { if ( ptr ) pclose(ptr); });