【问题标题】:Creating SQL table using C#使用 C# 创建 SQL 表
【发布时间】:2013-10-03 20:44:26
【问题描述】:

我想在一个循环中使用 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 的列是:日期(datetime)、值(int)
  • 表 2 的列是:日期 (datetime)、ID (varchar(255))、返回 (int)

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

谢谢!

【问题讨论】:

  • header 究竟包含什么?
  • 例如:header = {"Date", "ID"} 用于表 1。
  • 这完全取决于您如何确定列的类型,确定如何从标题字符串中获取列名和类型列表,然后返回并处理表。
  • @Mariam 那你怎么知道类型?
  • 这正是问题所在。让我们简化一下,让每个表的第一列为datetime,所有其他列为varchar(255)。那么有没有办法做到这一点?

标签: c# sql odbc


【解决方案1】:

您应该将问题分开,首先您需要获取定义列标题的对象列表,之后您可以遍历该列表并构建查询。

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));
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 2011-05-31
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多