0

CSVファイルをSQLデータベースにアップロードする際に問題が発生しました。イントラネットサイトでのファイルアップロード手法を使用してこれを実現しようとしています。イントラネットサイトは、私と別のユーザーがこれらのCSVをファイルアップロードできるようにするためのものです(私たちの1人が不在の場合)。

私は以下を使用しました。

    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にID列がある場合は、CSVから明示的に設定しないでください。データベースに重複が送信される可能性があります。また、数値列のように見えるものを引用符で囲んでいるため、型にいくつかの型の不一致があると思われます。不適切な引用符のエスケープの問題を回避するために、クエリの文字列連結をパラメータの使用に置き換えることを検討することをお勧めします(つまり、PartNameが「O'Reily'sautoparts」の場合はどうなりますか?)このようなものが機能する可能性があります。注意してください、私は長い間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 に答える