0

我有一个SqlBulkCopy导入 Excel 工作表的函数。它工作正常,除了我想向 Excel 电子表格中不存在的数据库表添加一个变量/常量值。我尝试过的一切都不起作用。

我一直在尝试添加变量MyUser,我一直收到同样的错误OleDBException Was Unhandled。被注释掉的 2 行是我最后 2 次尝试。我正在使用 asp.net 4.0、VS2010、SQL Server 2008。

Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & MyFile & ";Extended Properties=""Excel 12.0;HDR=YES;"""

Using connection As New System.Data.OleDb.OleDbConnection(excelConnectionString)

        Dim MyUser As String = UCase(My.User.Name)

        Dim command As New System.Data.OleDb.OleDbCommand("Select MA_Code FROM [" & cboSheet.Text & "$]", connection)
        'Dim command As New System.Data.OleDb.OleDbCommand("Select MA_Code, " & MyUser & " as MyUser FROM [" & cboSheet.Text & "$]", connection)
        'Dim command As New System.Data.OleDb.OleDbCommand("Select MA_Code, " + MyUser + " as MyUser FROM [" & cboSheet.Text & "$]", connection)
        connection.Open()

        Using dr As System.Data.OleDb.OleDbDataReader = command.ExecuteReader()

            Dim BKcn As New SqlClient.SqlConnection
            BKcn.ConnectionString = My.Settings.MyConnection
            BKcn.Open()
            Try
                Using bulkCopy As New System.Data.SqlClient.SqlBulkCopy(BKcn)
                    bulkCopy.BatchSize = 500
                    bulkCopy.BulkCopyTimeout = 3000
                    bulkCopy.DestinationTableName = cboSheet.Text

                    bulkCopy.ColumnMappings.Add("MA_Code", "MA_Code")
                    bulkCopy.WriteToServer(dr)
                End Using
4

1 回答 1

2

您需要在变量周围添加单引号。我希望 MyUser 的值就像您要的是一个带有帽子名称的列:

如果他的用户名是 Bob,则连接后的 SQL 将如下所示,并且没有 Bob 列:
Dim command As New System.Data.OleDb.OleDbCommand("Select MA_Code, Bob as MyUser FROM [" & cboSheet.Text & "$]", connection)

你希望它看起来像这样:

Dim command As New System.Data.OleDb.OleDbCommand("Select MA_Code, 'Bob' as MyUser FROM [" & cboSheet.Text & "$]", connection)

在你的代码中试试这个

Dim command As New System.Data.OleDb.OleDbCommand("Select MA_Code, '" & MyUser & "' as MyUser FROM [" & cboSheet.Text & "$]", connection)

布赖恩

于 2013-08-29T16:39:23.460 回答