0

我想在一个循环中使用 C# 创建两个 SQL 表。每个表都是不同的,并且其列名存储在一个数组中。每个列名数组实际上是从 csv 文件的标题中获取的。

 ### 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 的列是:Date (datetime), Value (int)
  • 表 2 的列是:日期 (datetime)、ID (varchar(255))、返回 (int)

请注意,这两个表具有不同类型的不同列。您对如何实现这一目标有什么建议吗?

谢谢!

4

1 回答 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));
    }
}
于 2013-09-27T14:23:12.087 回答