You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中编写带变量的SQLExecDirect SQL语句并生成完整语句

问题分析与解决

问题根源在于宽字符串输出的编码兼容性:在线编译器的std::wcout默认未配置本地化编码,导致无法正确解析并输出完整的宽字符串内容,实际上你的代码生成的sqlString是完整的,只是开头部分未被显示。

修复方案

方案1:配置std::wcout本地化编码

在main函数开头添加本地化配置,让wcout适配系统编码,同时统一使用宽字符串拼接避免窄转宽的潜在问题:

#include <iostream>
#include <sstream>
#include <locale> // 需引入locale头文件
using namespace std;

int main() {
    std::wcout.imbue(std::locale("")); // 配置本地化编码

    std::wstring email = L"test@gmail.com";
    std::wstring strategy = L"TestStrategy1";
    std::wstring CP = L"C";
    std::wstring watchListDate = L"2023-04-08";

    std::wstring watchListString = L"test1-930,test2-1045,test3-1500";
    std::wstring create_date = L"2023-05-10";

    std::wstringstream result1(L"Insert into watchList(emailID,strategy,CP,watchList_Date,watchList,create_date) values(");
    // 统一使用宽字符串常量拼接
    result1 << L"'" << email << L"', '" << strategy << L"', '" << CP << L"', '" << watchListDate << L"', '" << watchListString << L"', '" << create_date << L"')";
    std::wstring sqlString = result1.str();

    std::wcout << sqlString << std::endl;

    return 0;
}

方案2:改用窄字符串构造SQL语句

如果业务不需要宽字符,直接使用std::string和std::stringstream,兼容普通cout输出:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    std::string email = "test@gmail.com";
    std::string strategy = "TestStrategy1";
    std::string CP = "C";
    std::string watchListDate = "2023-04-08";

    std::string watchListString = "test1-930,test2-1045,test3-1500";
    std::string create_date = "2023-05-10";

    std::stringstream result1("Insert into watchList(emailID,strategy,CP,watchList_Date,watchList,create_date) values(");
    result1 << "'" << email << "', '" << strategy << "', '" << CP << "', '" << watchListDate << "', '" << watchListString << "', '" << create_date << "')";
    std::string sqlString = result1.str();

    std::cout << sqlString << std::endl;

    return 0;
}

关键安全提醒

直接拼接字符串构造SQL语句存在严重的SQL注入风险,生产环境中必须使用ODBC的参数化查询(SQLPrepare + SQLBindParameter),禁止将用户输入直接拼接到SQL语句中。

内容的提问来源于stack exchange,提问作者rawmud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:17:54