我需要将天气预报(温度)插入一个sql server数据库,以便远程控制建筑物的供暖。
步骤如下:
从rss源获取数据
把他们排成一列
连接到SQL数据库
将元素插入sql数据库
前三步我都做了,但最后一步我还是坚持了下来。
这个数组是从yahoo weather的rss提要创建的。

string[,] myarray1 = new string[5, 3];

数据库列的名称是:date、templow、temph
我正在尝试将此数组的元素插入到SQL Server数据库中。我已经挣扎了好几个小时,我不知道该怎么做。我在这个网站上看了很多解决方案,但都没有成功。
我试过:
foreach (string str2 in myarray1)
{
    var mycommand = new SqlCommand("INSERT INTO RSS2 VALUES(@Date, @Templow, @Temphigh)", myConnection);
    mycommand.Parameters.AddWithValue("@Date", str2);
    mycommand.Parameters.AddWithValue("@Templow", str2);
    mycommand.Parameters.AddWithValue("@Temphigh", str2);
    mycommand.ExecuteNonQuery();
}


for (k = 0; k < 5; k++)
{
    SqlCommand myCommand = new SqlCommand("INSERT INTO RSS2 (Date, Templow, Temphigh)" +
            "Values ('myarray1[k,0]','myarray1[k,1]','myarray1[k,2]')", myConnection);
    myCommand.ExecuteNonQuery();
}

还有其他很多…
这些解决方案都不正确。
这是我在c(我习惯于basic)中的第一个代码,所以请使用clement;-)

最佳答案

两种解决方案都很接近,但并不完全正确。
但是,我建议创建一个简单的类,称之为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; }
}

你可以这样初始化它,
WeatherInfo weather = new WeatherInfo("01/01/2014", "56F", "89F");

然后你可以使用一个数组,WeatherInfo[]
WeatherInfo[] infos = new WeatherInfo[5];

您仍然可以使用索引访问它,infos[0]以访问WeatherInfo对象。然后你可以更容易地使用你的第一个解决方案,
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();
}

或者你的第二个解决方案,
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();
}

但是,第二种解决方案存在一个称为SQL Injection的安全漏洞,其中一些攻击者可能会在1; SELECT * FROM table;值中插入不需要的sql(如string),然后将这些值传递给数据库,而无需验证这些命令的内容。

09-26 21:30
查看更多