2009-12-29 11 views
1

두 줄의 행이 있습니다 (헤더 행 포함) '|' 구분 된 텍스트 파일. 이것을 특정 SQL 테이블로 가져와야하고 명령에 어려움을 겪고 있습니다.SQL 테이블에 텍스트 파일 가져 오기

string sqltable = ("dbo.SLT_C" + "60" + "Staging"); 
string[] importfiles= Directory.GetFiles(@"K:\jl\load\dest", "*.txt") 
SqlConnection con = new SqlConnection("Data Source=" + "Cove" + ";Initial Catalog=" + "GS_Ava_MCase"+ ";Integrated Security=" + "SSPI"); 
con.Open(); 
foreach (string importfile in importfiles) 
{ 

} 

또는 어쩌면 나는이 모든 잘못된 길로 가고 있습니다.

+0

무엇이 문제입니까? – NotMe

+0

은 파일의 필드가 항상 동일합니까? 또는 포함 된 데이터 측면에서 각 파일이 다른가요? –

+0

은 내 접근법을 가능한 접근법으로 업데이트했습니다. 아직 완벽하지는 않습니다. 트랜잭션에도 적용 할 수는 있지만 작동해야하며 문제에 접근하는 방법을 알려줄 것입니다. –

답변

1

FileHelpers과 같은 기성품을 볼 수 있습니다. 이 무료 라이브러리를 사용하면 파일의 필드를 설명하는 클래스를 사용하여 파일의 구조를 정의한 다음 전체 파일을 해당 클래스 유형의 배열에 쉽게로드 할 수 있습니다.

일단 완료되면 개체를 반복하여 SQL Server에 저장하면됩니다.

또는 체크 아웃 SQL 대량 복사 옵션 :

참조 이 방법처럼 :

string sqltable = "dbo.SLT_C60Staging"; 

string[] importfiles = Directory.GetFiles(@"K:\jl\load\dest", "*.txt"); 

// try to wrap your ADO.NET stuff into using() statements to automatically 
// dispose of the SqlConnection after you're done with it 
using(SqlConnection con = new SqlConnection("Data Source=Cove;Initial Catalog=GS_Ava_MCase;Integrated Security=SSPI")) 
{ 
    // define the SQL insert statement and use parameters 
    string sqlStatement = 
     "INSERT INTO dbo.YourTable(DateField, TimeField, TextField) VALUES(@Date, @Time, @Text)"; 

    // define the SqlCommmand to do the insert - use the using() approach again 
    using(SqlCommand cmd = new SqlCommand(sqlStatement, con)) 
    { 
     // define the parameters for the SqlCommand 
     cmd.Parameters.Add("@Date", SqlDbType.DateTime); 
     cmd.Parameters.Add("@Time", SqlDbType.DateTime); 
     cmd.Parameters.Add("@Text", SqlDbType.VarChar, 1000); 

     // loop through all files found 
     foreach (string importfile in importfiles) 
     { 
     // read the lines from the text file 
     string[] allLines = File.ReadAllLines(importfile); 

     con.Open(); 

     // start counting from index = 1 --> skipping the header (index=0) 
     for (int index = 1; index < allLines.Length; index++) 
     { 
      // split up the data line into its parts, using "|" as separator 
      // items[0] = date 
      // items[1] = time 
      // items[2] = text 
      string[] items = allLines[index].Split(new char[] { '|' }); 

      cmd.Parameters["@Date"].Value = items[0]; 
      cmd.Parameters["@Time"].Value = items[1]; 
      cmd.Parameters["@Text"].Value = items[2]; 

      cmd.ExecuteNonQuery(); 
     } 

     con.Close(); 
     } 
    } 
} 

그게 작동해야합니다 - 당신은 질문이 라인에 어떤 데이터가 될지 정확히 알기에는 너무 모호합니다. 그리고 어떤 종류의 SQL 삽입 문이 필요하겠습니까 ...

+0

ruffley 30 파일이 유감스럽게 생각합니다. 각 파일에는 Date | Time | Text의 헤더 행이 있습니다. 각 파일에는 2 줄의 머리글 행 1 데이터 행만 있습니다. 구분 기호는 '|' 및 "" –

+0

나는 헤더 행과 데이터베이스 열을 매치시킬 필요가있다. –

+0

그게 나에게 "Inter '근처에 잘못된 구문이 있습니다. sqlStatement ="INTER INTO dbo.SLT_C60_Staging (dateField, timeField, TextField) VALUES (@date, @time, @Text) " –

0

텍스트 ODBC 드라이버를 사용하는 것도 효과가있을 수 있습니다. ODBC 관리자는 "Microsoft Access 텍스트 드라이버"를 선택할 수 있습니다. 구분 기호 유형을 선택할 수 있습니다. 데이터 소스를 설정 한 후 데이터 테이블로 가져옵니다. 거기에서 데이터를 SQL Server 테이블로 옮기는 것이 매우 간단해야합니다.