Both solutions are close, but not quite right.
However, I would suggest creating a simple class, call it WeatherInfo
,
public class WeatherInfo
{
public WeatherInfo(string date, string tempLow, string tempHigh)
{
this.Date = date;
this.TempLow = tempLow;
this.TempHigh = tempHigh;
}
public string Date { get; private set; }
public string TempLow { get; private set; }
public string TempHigh { get; private set; }
}
You can initialize it like this,
WeatherInfo weather = new WeatherInfo("01/01/2014", "56F", "89F");
Then you can use an array of these, WeatherInfo[]
,
WeatherInfo[] infos = new WeatherInfo[5];
You can still access it using indices, infos[0]
to get to the WeatherInfo
object. Then you can use your first solution a bit easier,
foreach (WeatherInfo info in infos)
{
var mycommand = new SqlCommand("INSERT INTO RSS2 VALUES(@Date, @Templow, @Temphigh)", myConnection);
mycommand.Parameters.AddWithValue("@Date", info.Date);
mycommand.Parameters.AddWithValue("@Templow", info.TempLow);
mycommand.Parameters.AddWithValue("@Temphigh", info.TempHigh);
mycommand.ExecuteNonQuery();
}
Or your second solution,
for (i = 0; i < infos.Length; i++)
{
SqlCommand myCommand = new SqlCommand(
"INSERT INTO RSS2 (Date, Templow, Temphigh)" +
"Values ('" + infos[i].Date + "','" + infos[i].TempLow + "','" + infos[i].TempHigh + "')",
myConnection);
myCommand.ExecuteNonQuery();
}
However, this second solution suffers from a security vulnerability known as SQL Injection, where some attacker might insert unwanted SQL (like 1; SELECT * FROM table;
) in the string
values, which you then pass to the database without verifying it is content for these type of commands.