0

我在将 CSV 文件上传到我的 SQL 数据库时遇到问题。我正在尝试通过 Intranet 站点上的文件上传技术来实现这一点。Intranet 站点供我和另一位用户上传这些 CSV 文件(以防我们中的一个人出局)。

我使用了以下内容;

    Dim errorList As String = String.Empty
    Dim returnValue As Integer = 0
    Dim SQLCon As New SqlClient.SqlConnection
    Dim SQLCmd As New SqlClient.SqlCommand
    Dim ErrString As String

    Dim countRecs As Integer = 0
    Dim batchid As Integer = GetNextBatchNumber("PartsImport")

    Using tf As New TextFieldParser(fileandpath)
        tf.TextFieldType = FileIO.FieldType.Delimited
        tf.SetDelimiters(",")


        SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
        SQLCon.Open()
        SQLCmd.CommandType = CommandType.Text
        SQLCmd.Connection = SQLCon

        Dim recAdded As String = Now.ToString
        Dim row As String()
        While Not tf.EndOfData

            Try
                row = tf.ReadFields()
                Dim x As Integer = 0
                If countRecs <> 0 Then
                    Try
                      SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
                      + " (ID,PartName,PartID,Price,ShipAddress) " _
                      + " values ('" + row(0) + "','" + row(1) + "','" _
                      + row(2) + "','" + row(3) + "','" + row(4) + "')"
                        SQLCmd.ExecuteNonQuery()

                    Catch ex As Exception
                        ErrString = "Error while Creating Batch Record..." & ex.Message
                    End Try
                End If

            Catch ex As MalformedLineException
                errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
            End Try
            countRecs = countRecs + 1
        End While

        SQLCon.Close()
        SQLCon.Dispose()
        SQLCmd.Dispose()

当我单击表单按钮上传时,它给了我一条成功消息,但是当我查看实际表格时,它仍然是空白的。

有任何想法吗?欣赏它

谢谢戴夫

4

2 回答 2

1
private void UploaddataFromCsv()
        {
            SqlConnection con = new SqlConnection(@"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
            string filepath = "C:\\params.csv";
            StreamReader sr = new StreamReader(filepath);
            string line = sr.ReadLine();
            string[] value = line.Split(',');
            DataTable dt = new DataTable();
            DataRow row;
            foreach (string dc in value)
            {
                dt.Columns.Add(new DataColumn(dc));
            }

            while ( !sr.EndOfStream )
            {
                value = sr.ReadLine().Split(',');
                if(value.Length == dt.Columns.Count)
                {
                    row = dt.NewRow();
                    row.ItemArray = value;
                    dt.Rows.Add(row);
                }
            }
            SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
            bc.DestinationTableName = "[Base].[PartsImport]";
            bc.BatchSize = dt.Rows.Count;
            con.Open();
            bc.WriteToServer(dt);
            bc.Close();
            con.Close();
        }
于 2012-09-18T16:14:16.833 回答
0

尝试捕获 SqlException 并查看您的请求是否存在格式问题。如果 ID 上有标识列,则不应从 CSV 显式设置它,因为这可能会导致潜在的重复项被提交到您的数据库。另外,我怀疑您的类型中有一些类型不匹配,因为您在似乎是数字列的地方加上引号。我建议您考虑将查询中的字符串连接替换为使用参数来避免不正确的引号转义问题(即,如果您的 PartName 为“O'Reily's auto parts”会发生什么?)这样的事情可能会奏效。请注意,我在 LINQ 世界中待了这么久,这里可能有一些语法错误。

SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
        SQLCon.Open()
        SQLCmd.CommandType = CommandType.Text  'Setup Command Type
        SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
                      + " (PartName,PartID,Price,ShipAddress) " _
                      + " values (@PartName, @PartID, @Price, @ShipAddress)'"
        Dim partNameParam = New SqlParameter("@PartName", SqlDbType.VarChar)
        Dim partIdParam = New SqlParameter("@PartID", SqlDbType.Int)
        Dim partPriceParam = New SqlParameter("@Price", SqlDbType.Money)
        Dim partAddressParam = New SqlParameter("@ShipAddress", SqlDbType.VarChar)
        SQLCmd.Parameters.AddRange(  {partNameParam, partIdPAram, partPriceParam, partAddressParam})
        SQLCmd.Connection = SQLCon

        Dim recAdded As String = Now.ToString()
        Dim row As String()
        While Not tf.EndOfData

            Try
                row = tf.ReadFields()
                Dim x As Integer = 0
                If countRecs <> 0 Then
                    Try
                       partNameParam.Value = row[1]
                       partIdParam.Value = row[2]
                       partPriceParam.Value = row[3]
                       partAddressParam.Value = row[4]

                       SQLCmd.ExecuteNonQuery()

                    Catch ex As Exception
                        ErrString = "Error while Creating Batch Record..." & ex.Message
                    End Try
                End If

            Catch ex As MalformedLineException
                errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
            End Try
            countRecs = countRecs + 1
        End While

        SQLCon.Close() 'TODO: Change this to a Using clause
        SQLCon.Dispose() 
        SQLCmd.Dispose() 'TODO: Change this to a Using clause

话虽如此,如果您要插入大量项目,批量复制示例是一个更好的答案。

于 2012-09-18T20:34:53.737 回答