首页 > 解决方案 > 尝试使用 C++ 在 SQL Server 中创建新表时出错

问题描述

这是一个创建与 SQL Server 的连接并尝试创建新表的函数。

我尝试了我能想到的一切,现在我一无所知。与服务器的连接工作正常,但总是出现“无法创建新表”的消息。(我已经尝试查看有关该主题的其他 Stack Overflow 帖子)。

它给了我这个错误:

在此处输入图像描述

这是我的主要和错误的图片,它表明一个简单的查询有效:

在此处输入图像描述

   void DB::runQuery(string SQLQuery)
{


    SQLCHAR retConString[1024]; // Conection string
    switch (SQLDriverConnect(SQLConnectionHandle, NULL, (SQLCHAR*)"DRIVER={SQL Server}; SERVER=localhost, 1433; DATABASE=myDB; UID=myID; PWD=1234;", SQL_NTS, retConString, 1024, NULL, SQL_DRIVER_NOPROMPT)) {
        // Establishes connections to a driver and a data source
    case SQL_SUCCESS:
        break;
    case SQL_SUCCESS_WITH_INFO:
        break;
    case SQL_NO_DATA_FOUND:
        showSQLError(SQL_HANDLE_DBC, SQLConnectionHandle);
        retCode = -1;
        break;
    case SQL_INVALID_HANDLE:
        showSQLError(SQL_HANDLE_DBC, SQLConnectionHandle);
        retCode = -1;
        break;
    case SQL_ERROR:
        showSQLError(SQL_HANDLE_DBC, SQLConnectionHandle);
        retCode = -1;
        break;
    default:
        break;
    }

    if (retCode == -1)
        print("An error occurred");

    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, SQLConnectionHandle, &SQLStatementHandle))
        // Allocates the statement
        print("could not allocate the statement");

    if (SQL_SUCCESS != SQLExecDirect(SQLStatementHandle, (SQLCHAR*)SQLQuery.c_str(), SQL_NTS)) {
        // Executes a preparable statement
        showSQLError(SQL_HANDLE_STMT, SQLStatementHandle);
        print("could not execute the statement");
    }
    else {
        char name[256];
        int age;
        while (SQLFetch(SQLStatementHandle) == SQL_SUCCESS) {
            // Fetches the next rowset of data from the result
            SQLGetData(SQLStatementHandle, 1, SQL_C_DEFAULT, &name, sizeof(name), NULL);
            SQLGetData(SQLStatementHandle, 2, SQL_C_DEFAULT, &age, sizeof(age), NULL);
            // Retrieves data for a single column in the result set
            cout << name << " " << age << endl;
        }
    }


}

标签: c++sqlsql-server

解决方案


推荐阅读