使用C ++将.csv上传到SQL Server

时间:2013-08-16 15:42:32

标签: c++ sql csv upload permissions

我正在使用Windows 7下的Visual Studio 2012 Express版本。另一方面,SQL服务器是“SQL Server 2008 R2”。

我尝试过遵循C ++代码:

#include <iostream>
#include <windows.h>
#include <string>
#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>
using namespace std;

void main()
{
    clock_t start = clock();

    SQLHANDLE sqlevent, sqlconnection, sqlstatement;

    if(SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlevent))       
    {
        cout<<"The sqlevent has failed to be created."<<endl;
        system("pause");
        return;
    }


    if(SQL_SUCCESS != SQLSetEnvAttr(sqlevent, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
    {
        cout<<"The sqlevent has failed to be initialized."<<endl;
        system("pause");
       return;
    }

    if(SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlevent, &sqlconnection))
    {
        cout<<"The sqlconnection has failed to be created."<<endl;
        system("pause");
        return;
    }

    SQLCHAR retstring[10000];
    SQLDriverConnect(sqlconnection, NULL, (SQLCHAR*)("DRIVER={SQL Server Native Client 10.0};SERVER=DATASERVER;DATABASE=DATABASE;UID=CrystalReports;PWD=PASSWORD"), SQL_NTS, retstring, 10000, NULL, SQL_DRIVER_NOPROMPT);  

    if(SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlconnection, &sqlstatement))
    {
        cout<<"The sqlstatement has failed to be created."<<endl;
        system("pause");
        return;
    }

    string commandline;

    commandline = "CREATE TABLE NEW_TABLE ( ID VARCHAR(10), AGE FLOAT) GO ";

    if(SQL_SUCCESS != SQLExecDirect(sqlstatement, (SQLCHAR*)(commandline.c_str()), SQL_NTS))
    {
        cout<<"The create table sql command has failed to excute."<<endl;
        system("pause");
        return;
    }

    commandline = "BULK INSERT NEW_TABLE FROM 'C:/temp/datafile.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n') GO";

    if(SQL_SUCCESS != SQLExecDirect(sqlstatement, (SQLCHAR*)(commandline.c_str()), SQL_NTS))
    {
        cout<<"The import sql command has failed to excute."<<endl;
        system("pause");
        return;
    }

    clock_t end = clock();

    cout<<"Import from .csv file to SQL Server costs "<<((end-start)/double(CLOCKS_PER_SEC))<<" seconds."<<endl;

    system("pause");

    return;

}

当我运行此代码时,程序始终在create table停止。

我想知道我是否没有创建表的权限,因此我手动创建了一个表。并且有一个警告弹出:

enter image description here

我是否知道上图中显示的警告是否是我的代码失败的原因,或者我只是在代码中犯了错误?

非常感谢。

2 个答案:

答案 0 :(得分:0)

谁拥有数据库?您需要找到数据库管理员并让他们授予您将表添加到数据库的权限。

答案 1 :(得分:0)

您可能想要检查该帐户已获得哪些权限。

您需要INSERT以及BULKADMIN server role的权限。

但正如您在this post中所看到的那样,根据文件的位置,它会变得毛茸茸。你可以在