c# mysql 数组_如何使用C#将数组元素插入SQL Server数据库?

欧阳博超
2023-12-01

两种解决方案都很接近,但并不完全正确.

但是,我建议创建一个简单的类,称之为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];

您仍然可以使用indices,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的安全漏洞,其中一些攻击者可能会在字符串值中插入不需要的SQL(如1; SELECT * FROM table;),然后将其传递给数据库而不验证它是否为这些内容命令类型.

 类似资料: