我想在不同的表中执行insert到数据库。我在我的文件中的每条记录都分配有表标识符,这些标识符将用作键。现在我所做的是使它成为通用方法,我创建了一个file.txt,其中我已经使用表名指定了所有标识符。并将其存储到字符串字符串中。
所以,我的例子中有一些例子如下:
表标识符,表名
表标识符,表名
然后我创建了另一个string字典作为键(注意:我使用了前一个字典值作为该字典的键),并将字符串列表作为值来获取表名的列名。
所以,不,我在下面有一些这样的东西将数据存入我的字典:
表名,列名IEnumerable
表名,列名IEnumerable
然后, datafile.txt包含数据作为管道分隔,我将它们拆分并保存到KVP的字符串列表和字符串列表中。正如我之前提到的,我的数据文件中有表标识符。所以我在KVP中使用它们作为键,并将拆分值存储到字符串列表中。
所以,不,我在下面有一些这样的东西将样本数据存入我的KVP字符串列表,字符串列表:
表标识符,IEnumerable值
表标识符,IEnumerable值
现在做了一半的工作,我陷入了我的最终问题:
现在我将所有标识符,表名,列名和值与我一起放入字典和列表中。唯一要做的就是匹配并合并记录和DUMP吧!
匹配:我曾想过匹配KVP s key with the dictionary
键列表,然后使用这些值作为键来获取列名。
预期情景图片:
列表[[列表<列名>;],[字符串值列表]]
我的代码:
DataTable dt = null;
SqlConnection cn = null;
SqlDataReader dataReader = null;
SqlBulkCopy bulkInsert = null;
StreamReader reader = null;
string path = string.Empty;
public void test()
{
string TableIdentiferFilepath = HttpContext.Current.Server.MapPath("/testfile/TableIdentifer.txt");
Dictionary<string, string> TableIdentifer_TableName = null;
Dictionary<string, List<string>> Table_Name_ColumnName = null;
using (reader = new StreamReader(TableIdentiferFilepath))
{
TableIdentifer_TableName = new Dictionary<string, string>();
Table_Name_ColumnName = new Dictionary<string, List<string>>();
while (!reader.EndOfStream)
{
string[] curr = reader.ReadLine().Split(new string[] { ",", "\r\n" }, StringSplitOptions.None);
TableIdentifer_TableName.Add(curr[0], curr[1]);
using (cn = new SqlConnection(ConString.Connection.conn))
{
cn.Open();
if (cn.State == ConnectionState.Open)
{
string query = string.Format("select column_name from information_schema.columns where table_name = '{0}' order by ordinal_position", curr[1].ToString());
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter da = new SqlDataAdapter(query, cn))
{
using (dt = new DataTable())
{
da.Fill(dt);
List<string> dataColumns = dt.AsEnumerable().Select(r => r.Field<string>("column_name")).ToList();
Table_Name_ColumnName.Add(curr[1], dataColumns);
}
}
}
}
}
}
}
string path = HttpContext.Current.Server.MapPath("/TextFile/DataSample.txt");
List<KeyValuePair<string, List<string>>> KVPValues = new List<KeyValuePair<string, List<string>>>();
using (reader = new StreamReader(path))
{
while (!reader.EndOfStream)
{
string[] arr = reader.ReadLine().Split(new string[] { "|", "\r\n" }, StringSplitOptions.None);
var collValues = new List<string>();
KVPValues.Add(new KeyValuePair<string, List<string>>(arr[0], arr.Skip(1).AsEnumerable().ToList()));
foreach (var item in TableIdentifer_TableName)
{
foreach (var item2 in Table_Name_ColumnName.Where(c => c.Key == item.Value))
{
var curr_val = item2.Value;
var currKey = KVPValues.Where(p => p.Key == item.Key).ToList();
}
}
}
}
}
这是一幅大图!希望现在人们会明白我想要达到的目标。