2016-08-01 40 views
0

我目前有一些問題與我的CSV到SQL轉換器。這是我學習C#的第三週,我開始掌握一些東西,但這已經超出了我的頭腦。CSV到SQL轉換器

我想要做的是將頂部行/標題拆分成每個單獨的標題,然後通過該代碼,而不是像我這樣手動輸入它。下面你可以看到我迄今爲止編寫的一些代碼。

private void Form1_Load(object sender, EventArgs e) 
    { 
     try 
     { 
      // your code here 
      string CSVFilePathName = @"C:\\CSV\\reg.csv"; 
      string[] Lines = File.ReadAllLines(CSVFilePathName); 
      string[] Fields; 
      //1st row must be column names; force lower case to ensure matching later on. 
      // get regs from filename 
      // get fieldnames from Lines[0] (first line of file) 
      // create a loop for fields array 
      string hdr = Lines[0]; 
      for (int i = 1; i < Lines.Length; i++) 
      { 
       Fields = Lines[i].Split(new char[] { ',' }); 
       CSVTextBox.AppendText(Fields[0] + "," + Fields[1] + "," + Fields[2] + "," + Fields[3] + Environment.NewLine); 
       // need a for loop for each field 
       // for (
            SQLTextBox.AppendText("INSERT INTO[dbo].[REGS]([SESTYPE],[REG],[LFL],[SUBVER]) VALUES('" + Fields[3] + "'" + Fields[0] + "'" + Fields[1] + "'" + Fields[2] + ")" + Environment.NewLine); 
       //  } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error is " + ex.ToString()); 
      throw; 
     } 

    } 

這一切都運行在這一刻,我只是努力讓標題成爲代碼的一部分。任何幫助,將不勝感激。

乾杯,

回答

1

第一次:刪除try catch。如果你得到一個例外,你應該閱讀,理解和清除。 對於你的SQLTextBox:我推薦使用String.Format函數。這允許您創建具有不同值的字符串,但是更容易閱讀。

對於標題:使用您的變量hdr這應該包含標題。然後你可以通過string.Split(',')或string.Split(';')拆分它,這取決於你的分隔符