gpt4 book ai didi

c# - 将列表保存到数据库

转载 作者:太空宇宙 更新时间:2023-11-03 21:55:54 24 4
gpt4 key购买 nike

这是我目前所拥有的:

Veza.Open();
SqlCommand zadnjaN = new SqlCommand("SELECT TOP 1 id_n FROM Narudzba ORDER BY id_n DESC", Veza);
var id_zn = zadnjaN.ExecuteScalar(); //get 1 value for id_zn (last one entered)
List<int> proizvodi = new List<int>();
proizvodi = (List<int>)Session["kosarica"];
SqlCommand kupnja1 = new SqlCommand("INSERT INTO NarudzbaItemi ([narudzbaID], [proizvodID]) VALUES (@id_zn, @pro)", Veza);
for (int i = 0; i < proizvodi.Count; i++)
{
kupnja1.Parameters.AddWithValue("pro", proizvodi[i]); //also tried @pro
kupnja1.Parameters.AddWithValue("id_zn", id_zn); //@id_zn
kupnja1.ExecuteNonQuery();
}
Veza.Close();

我收到一条消息,说变量名@pro 已全部声明。关键是,我需要将一个 int 项目列表插入到列 proizvodID 中,但是我多次在该列中插入一个值,我需要在列 narudzbaID 中多次插入一个不变的值,我从另一个表中获得最后增加的值。所有 3 列都是 int,Session 是 List int。使用 asp.net、c#、sql server 2008。

最佳答案

您不断在循环中添加参数。在第二次迭代中,@pro 已经定义。

试试这个:

Veza.Open();
object id_zn; //get 1 value for id_zn (last one entered)
using (SqlCommand zadnjaN = new SqlCommand("SELECT TOP 1 id_n FROM Narudzba ORDER BY id_n DESC", Veza))
{
id_zn = zadnjaN.ExecuteScalar();
}
List<int> proizvodi = (List<int>)Session["kosarica"];
using (SqlCommand kupnja1 = new SqlCommand("INSERT INTO NarudzbaItemi ([narudzbaID], [proizvodID]) VALUES (@id_zn, @pro)", Veza))
{
kupnja1.Parameters.Add("pro");
kupnja1.Parameters.Add("id_zn");
for (int i = 0; i < proizvodi.Count; i++)
{
kupnja1.Parameters["pro"].Value = proizvodi[i]; //also tried @pro
kupnja1.Parameters["id_zn"].Value = id_zn; //@id_zn
kupnja1.ExecuteNonQuery();
}
}
Veza.Close();

关于c# - 将列表保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12315022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com