我需要保存一个sql SELECT语句,该语句包括数据库中的所有表及其列。该语句工作正常,我可以从所需的表和列中获取所有名称。
结果如下:(这只是伪东西)
table_Name Column_name
- CallerIP DT
- CallerIP ID
- CallerIP IP
- queueObject Action
- queueObject Attempt
- queueObject DestinationAddress
- queueObject ID
我可以将其保存到Dictionary
中,其中tableName是String
,而Colum_Names是List
中Strings
的
private Dictionary<string, List<string>> rowAndTables = new Dictionary<string, List<string>>();
这是我的代码,应将所有表和行添加到字典中
//Some code above, that doesnt matter here
command = new SqlCommand(sqlSelect, SqlConnector.getConnection());
command.Connection = SqlConnector.getConnection();
reader = command.ExecuteReader();
while (reader.Read()) {
if (tempTableName.Equals(reader.GetString(0)) == false) {
tempTableName = reader.GetString(0);
tempColumn = reader.GetString(1);
Console.WriteLine(tempTableName);
Console.WriteLine(tempColumn);
} else {
tempColumn = reader.GetString(1);
Console.WriteLine(tempColumn);
}
}
除了打印所有表和列之外,这没有任何作用。 结果如下: //控制台...
CallerIP //Table
DT
ID
IP
queue_object //Table
Action
Attempt
DestinationAddress
ID
所以打印很好。
现在,我正在努力将其添加到Dictionary
中。
有人可以帮忙吗?
我想我所做的任何事都没有道理,只会使任何人感到困惑。
答案 0 :(得分:1)
好吧,如果您想填写字典
private Dictionary<string, List<string>> rowAndTables =
new Dictionary<string, List<string>>();
您应该稍微修改代码:
...
//DONE: wrap IDisposable (command) into using in order to release resources
using (var command = new SqlCommand(sqlSelect, SqlConnector.getConnection())) {
// Redundant, can be dropped
command.Connection = SqlConnector.getConnection();
using (var reader = command.ExecuteReader()) {
//TODO: check if the key and value are correct ones
string key = Convert.ToString(reader[0]);
string value = Convert.ToString(reader[1]);
// Do we have the key (and corresponding list) in the dictionary?
if (rowAndTables.TryGetValue(key, out var list))
// yes - we should add the value to the existing list
list.Add(value);
else
// no - we have to create key and list with value
rowAndTables.Add(key, new List<string>() {value});
}
}