C ++ odbc查询实际上没有插入记录

时间:2015-06-05 23:14:08

标签: c++ sql-server odbc

我目前正在尝试构建一个简单的C ++程序,以便将记录插入到MS Sql Server数据库中。代码执行和返回代码表明技术上工作的东西,但实际上没有记录插入数据库。我很遗憾可能导致这个问题。司机也许?

最初我打算使用预备语句并避免任何字符串复制,但我似乎无法使这些语句正常工作。因此,为了测试是否会发生任何事情,我构建了一个查询,如下所示。这不是最好的方法而不是我想要的方法,但我似乎甚至无法将记录插入数据库。

返回代码并不表示连接有问题(请注意,我已经更改了实际的连接信息)甚至执行了查询,这使我可能需要提交?也是为什么我可能倾向于认为它是驱动程序。想法?

以下是代码:

stdafx.h中

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>



// TODO: reference additional headers your program requires here
#include <Windows.h>
#include <winnt.h>
#include <sqlext.h>
#include <rpc.h>
#include <iostream>

#pragma comment(lib, "rpcrt4.lib")

和testCamel2Db.cpp

// testCamel2Db.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

INT connectDb(VOID);

int _tmain(int argc, _TCHAR* argv[])
{
    connectDb();
    return 0;
}

INT connectDb (VOID)
{
    RETCODE rc; //ODBC return code
    HENV henv;  //environment handle
    HSTMT hstmt;//statement handle
    HDBC hdbc;  //connection handle

    SQLAllocEnv(&henv);
    SQLAllocConnect(henv, &hdbc);

    rc = SQLDriverConnect(
        hdbc,
        NULL,
        (unsigned char*)"DRIVER={SQL Server};SERVER=server.name.edu,3433;DATABASE=camel2;UID=username;PWD=password;",
        SQL_NTS,
        NULL,
        0,
        NULL,
        SQL_DRIVER_COMPLETE);

    if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
    {
        //error handling here
        std::cout << "no connection created.";
        return 1;
    }


    //create a uuid
    UUID uuid;
    UuidCreate(&uuid);
    unsigned char* uuidStr;
    UuidToStringA(&uuid,&uuidStr);
    INT quotedUuidSize = strlen((char*)uuidStr) + 2;
    char* quotedUuidStr = new char[quotedUuidSize +1];
    memset(quotedUuidStr, 0, sizeof(char) * quotedUuidSize + 1);
    strcat(quotedUuidStr, "'");
    strcat(quotedUuidStr, (char*)uuidStr);
    strcat(quotedUuidStr, "'");

    //admin_user variable
    LPSTR adminUser;
    adminUser = "'Active Directory'";

    //build a query
    LPSTR sql = "INSERT cw_ResetCheck (ResetUID, AdminUser ) values (";
    INT queryStrSize = strlen(sql) + strlen((char*)quotedUuidStr) + strlen(adminUser) + 2;
    char* queryStr = new char[queryStrSize + 1];
    memset(queryStr, 0, sizeof(char) * (queryStrSize + 1));
    strcat(queryStr,sql);
    strcat(queryStr,(char*)quotedUuidStr);
    strcat(queryStr,",");
    strcat(queryStr,adminUser);
    strcat(queryStr,")");

    std::cout << queryStr << "\n";

    rc = SQLAllocStmt(hdbc,&hstmt);

    std::cout << uuidStr;

    rc = SQLExecDirect(hstmt, (SQLCHAR*)queryStr, SQL_NTS);

    if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
    {
        std::cout << "query failed";
        return 1;
    } 
    else
    {
        std::cout << "uid created: ";
        std::cout << uuidStr;
    }

    //close database
    SQLFreeStmt(hstmt,SQL_DROP);
    SQLDisconnect(hdbc);
    SQLFreeConnect(hdbc);

    return 0;
}

0 个答案:

没有答案