使用C for MFC Dialog Base App在MySQL中插入一行

Insert a row in MySQL using C++ for MFC Dialog Base App

我有2个变量,我想将它们的值插入MySQL数据库,但是我不知道该怎么做。

这是到目前为止我的全部代码,请更正/建议:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
void RegistrationForm::Register()
{
    istifadeciAdi.GetWindowText(i_ad);
    par.GetWindowText(i_par);
    parTekrar.GetWindowText(i_par_tekrar);

if (istifadeciAdi.GetWindowTextLength() != 0) // if you can please write this line better.
{
    if (i_parol == i_parol_tekrar)
    {
        MySQL_Driver *driver;
        Connection *dbConn;
        Statement *statement;
        //ResultSet *result; // I don't need this line any more
        //PreparedStatement *ps;

        driver = get_mysql_driver_instance();
        dbConn = driver->connect("host","u","c");

        dbConn->setSchema("mfc_app_database");
        statement = dbConn->createStatement();

        statement->executeQuery("INSERT INTO users(`username`, `password`) VALUES (/* how to use i_ad and i_par as variable to set column value? */)"); // executes the user"input"

        /*ps = dbConn->prepareStatement("INSERT INTO users(`username`, `password`, `name`) VALUES (?)");
        ps->setString(1,"cccc");
        ps->setString(2,"ffff);*/


        //delete result;
        //delete[] result;
        /*delete ps;
        delete[] ps;*/

        delete statement;
        delete[] statement; // don't use this line in your program as me
        delete dbConn;
        delete[] dbConn; // don't use this line in your program as me
    }
    else
        MessageBox(L"?ifr? d?qiq t?krar olunmal?d?r.", L"X?b?rdarl?q", MB_ICONWARNING);
}
else
    AfxMessageBox(L"Bo? qoymaq olmaz.");
}

编辑

没有任何错误。但是当我点击(注册)按钮时,它说:
Program stopped working
然后单击Debug按钮后,我进入到我编写的插入查询行。

p.s对不起,我的英语不好。


使用CString进行查询。
例如:

1
2
CString strQuery;
strQuery.Format(_T("INSERT INTO users(`username`, `password`) VALUES ('%s', '%s')"),i_ad, i_par);

executeQuery(或其他查询命令)中使用此查询字符串之前,必须将其转换为std::string。因为execute, executeQuery and executeUpdate命令仅接受std::string,所以添加以下行:

CT2CA tempString(query);

std::string query(tempString);

并在执行命令

中使用此字符串

1
statement->executeQuery(query);

该MySQL连接器的文档说,对于不返回结果集的查询,请使用statement::execute();对于只有一行结果集的查询,请使用statement::executeQuery()

因此对于SQL INSERT INTO,也许您的问题是您应该使用execute