我想在循环中使用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
}
想象一下:
请注意,这两个表具有不同的列,具有不同的类型。 您对如何实现这一目标有什么建议吗?
谢谢!
答案 0 :(得分: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));
}
}