2012-09-18 3 views
0

SQL 데이터베이스에 CSV 파일을 업로드하는 데 문제가 있습니다. 필자는 인트라넷 사이트에서 파일 업로드 기술을 통해이 작업을 수행하려고합니다. 인트라넷 사이트는 나와 다른 사용자가이 CSV 파일을 업로드 할 수있는 기능을 제공합니다.파일 작성 방법 인트라넷 VB.NET 사이트의 SQL 데이터베이스에 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() 

업로드 할 때 양식 버튼을 클릭하면 성공 메시지가 표시되지만 실제 표를 보면 여전히 비어 있습니다.

아이디어가 있으십니까? 그것을 감사

감사 데이브

+1

표시되지 않는 오류가있을 수 있습니다. SQL 프로필러를 실행하여 실제로 어떤 SQL이 데이터베이스에 도달했는지 확인할 수 있습니다. 또한 CSV 가져 오기에 문제가있을 수 있습니다. 나는 최근에이 CSV 라이브러리를 사용했고 그것을 사랑했습니다 : https://github.com/JoshClose/CsvHelper. NuGet에서도 사용할 수 있습니다. – Gromer

+1

또한 더 많은 코드를 표시하고 서식을 지정해야합니다. – Gromer

+0

동일한 연결을 사용하여 select 문을 실행하면 어떻게됩니까? SQLCmd.CommandText = "SELECT * [Base]. [PartsImport]"; –

답변

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(); 
     } 
+0

좋은 예이지만 당신이하고있는 일을 설명하기 위해 답에 약간의 설명을 추가하는 것이 좋습니다. –

0

는 SQLEXCEPTION을 잡기와 귀하의 요청에 서식 문제가있을 경우보고보십시오. ID에 ID 열이있는 경우 CSV에서 명시 적으로 설정하지 않아야 잠재적 인 중복이 데이터베이스에 제출 될 수 있습니다. 또한 숫자 열로 보이는 것을 따옴표로 묶으므로 형식에 유형 불일치가 있다고 의심됩니다. 부적절한 따옴표 이스케이프 (예 : "O'Reily의 자동차 부품"으로 PartName을 사용하면 어떻게됩니까?)와 관련된 문제를 피하기 위해 매개 변수를 사용하여 쿼리의 문자열 연결을 바꾸는 것이 좋습니다.) 이와 같은 문제가 발생할 수 있습니다. 참고, 필자는 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 

삽입 할 항목이 많으면 대량 복사 예제가 더 좋은 답변입니다.

관련 문제