CString到std :: string或sql :: SQLString转换 - C ++

问题描述 投票:0回答:2

我正在尝试将来自CComboBox的CString变量转换为std::stringsql::SQLString,以便在SQL查询中设置它(使用Mysql Connector C ++)。所以,这里我的代码:

CComboBox *pComboRule = (CComboBox*)GetDlgItem(ID_EDIT_RULE);
CComboBox *pComboAg1 = (CComboBox*)GetDlgItem(ID_EDIT_AG1);
CComboBox *pComboAg2 = (CComboBox*)GetDlgItem(ID_EDIT_AG2);
CComboBox *pComboAg3 = (CComboBox*)GetDlgItem(ID_EDIT_AG3);

CString &AG1 = CString(_T("A string"));
CString &AG2 = CString(_T("A string"));
CString &AG3 = CString(_T("A string"));
CString str;

pComboAg1->GetLBText(pComboAg1->GetCurSel(), AG1);
pComboAg2->GetLBText(pComboAg2->GetCurSel(), AG2);
pComboAg3->GetLBText(pComboAg3->GetCurSel(), AG3);


try {

    std::string s = CStringA(AG1);

    sql::PreparedStatement *pstmt = con->prepareStatement("SELECT `nAccessIdn` FROM `base`.`tb_table` WHERE `field` IN (?, ?, ?) LIMIT 3");
    pstmt->setString(1, s);
    pstmt->setString(2, s);
    pstmt->setString(3, s);
    sql::ResultSet *res = pstmt->executeQuery();

    if (res->rowsCount() != 0) {

        while (res->next())
        {

            str.Format(_T("AG : %s\r\n"), res->getString(1));
            OutputDebugString(str);

        }

    }

}
catch (const std::bad_alloc& e) {
    CString itemString;
    itemString.Format(_T("SQLException %s"), CString(e.what()));
    MessageBox(itemString, _T("Failed Logon Attempt"), MB_OK | MB_ICONERROR);
}

我已经尝试过很多东西了

std::string s((LPCTSTR)AG1);

要么

std::basic_string<TCHAR>

要么

std::string std(somStr, someStr.GetLength());

要么

CT2A(cst.GetString());

要么

char* myStr = "This is a C string!";
std::string myCppString = myStr;

等等...

有谁知道成功的方法?

细节 :

Visual Studio 2017社区版 - Unicode项目 - 运行时库:/ MDd

非常感谢你的帮助 :)

编辑:C ++新手,代码更新。

c++ string unicode type-conversion c-strings
2个回答
1
投票
CString &AG1 = CString(_T("A string"));
pComboAg1->GetLBText(pComboAg1->GetCurSel(), AG1);

这在很多方面都是错误的。 AG1是指向某些固定数据的指针,你用其他东西设置AG1

只需使用:

CString AG1;
pComboAg1->GetLBText(pComboAg1->GetCurSel(), AG1);

您的SQL数据应该是UTF-8。如果要创建新的MFC程序,则默认启用UNICODE选项(UTF-16)。

从数据库获取数据:

std::string str;
//get str from databases
CStringW atl = CA2W(str.c_str(), CP_UTF8);
combobox.AddString(atl);

将数据发送到数据库:

CString AG1;
combobox.GetLBText(0, AG1);
std::string str = CW2A(AG1, CP_UTF8);
...

在极少数情况下,数据可能是ANSI,在这种情况下删除CP_UTF8标志。


-1
投票

CString到std :: string

CString cstr = L"Hello";
std::string str = std::string(CStringA(cstr));

CString到sql :: SQLString

CString cstr = L"Hello";
std::string str = std::string(CStringA(cstr));
sql::SQLString sqstr = sql::SQLString(str.c_str());
© www.soinside.com 2019 - 2024. All rights reserved.