2013-09-27 59 views
0

我想在循環內使用C#創建兩個SQL表格。每個表都不同,並且其列名存儲在一個數組中。每個列名稱數組實際上是從csv文件的標題獲得的。使用C#創建SQL表格

### fnames is an array of file paths (2 csv files) 
foreach string f in fnames) 
{ 
     ## snip 
     using (StreamReader rdr = new StreamReader(f)) 
     { 
      string header = read.line(); ## This is the array of table columns 
     } 
     string tab = Path.GetFileNameWithoutExtension(f); 
     string query = @"create table "+ tab + ..."; #I am not sure how to write the column names and types dynamically 
} 

想象一下:

  • 爲表1的列有:日期(日期時間),值(INT)
  • 爲表2的列有:日期(日期時間),ID(VARCHAR (255)),Return(int)

請注意,這兩個表具有不同類型的不同列。 你有什麼建議如何實現這一目標?

謝謝!

+0

什麼'header'包含完全? –

+0

例如:表頭1的'header = {「Date」,「ID」}' – Mayou

+1

這一切都取決於您如何確定列的類型,計算出如何獲取列名列表以及然後返回並解決表的創建。 –

回答

2

您應該將問題分開,首先需要獲取定義列標題的對象列表,然後您可以遍歷該列表並構建查詢。

class HeaderInfo 
{ 
    public HeaderInfo(string header) 
    { 
     throw new NotImplementedException("Parse out your header info here and populate the class") 
    } 

    public string Name {get; private set;} 
    public string TypeInfo {get; private set;} 
} 

private List<HeaderInfo> ParseHeader(string header) 
{ 
    var headerInfo = new List<HeaderInfo>(); 
    string[] headerItems = //Split your header line in to indvidual items some how 
    foreach(headerItem in headerItems) 
    { 
     headerInfo.Add(new HeaderInfo(headerItem)); 
    } 
    return headerInfo; 
} 

private string TableString(List<HeaderInfo> headerInfo) 
{ 
    StringBuilder sb = new StringBuilder(); 

    foreach(var info in headerInfo) 
    { 
     sb.AppendFormat("{0} {1}, ", info.Name, info.TypeInfo); 
    } 

    sb.Remove(sb.Length -2, 2); //Remove the last ", " 

    return sb.ToString(); 
} 

private void YourMethod(string[] fnames) 
{ 
    ### fnames is an array of file paths (2 csv files) 
    foreach string f in fnames) 
    { 
     ## snip 
     List<HeaderInfo> headerInfo; 
     using (StreamReader rdr = new StreamReader(f)) 
     { 
       string headerLine = read.line(); ## This is the array of table columns 
       headerInfo = ParseHeader(headerLine); 
     } 
     string tab = Path.GetFileNameWithoutExtension(f); 
     string query = String.Format(@"create table [{0}] ({1})", tab, TableString(headerInfo)); 
    } 
}