So method GetAllData is one of my universal methods for connecting to the database and here, since I have to add mupltiple records in once to the database I need to have one connetion with multiple commands to run. So my question is does this way of connection closes the database correctly, or if you have any improvments to my code please share with me.
var conn = new SqlConnection(ConnString);
conn.Open();
var data = new Dictionary<string, List<object>>();
foreach (var h in hours)
{
data += SqlUniversal.GetAllData(query,//idk how I will collect the data yet... i know += wouldnt work for dictionary
new[] {
//some parameters
},
conn);
}
//Here is the method, above is how I call it.
public static Dictionary<string, List<object>> GetAllData(string command, SqlParameter[] pars, SqlConnection conn)
{
if (conn == null)
{
conn = new SqlConnection(ConnString);
conn.Open();
}
var res = new Dictionary<string, List<object>>();
using (conn)
{
using (var cmd = new SqlCommand(command, conn))
{
cmd.Parameters.AddRange(pars);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
for (var i = 0; i < reader.VisibleFieldCount; i++)
{
if (reader.GetValue(i) == DBNull.Value)
continue;
var name = reader.GetName(i);
if (res.ContainsKey(name))
res[name].Add(reader.GetValue(i));
else
res.Add(name, new List<object> {reader.GetValue(i)});
}
return res;
}
}
}
}