我試圖插入一些名單到我的數據庫(微軟),但我得到這個運行時錯誤失敗試圖插入我的數據
未能參數值從List`1轉換成的Int32 。
這裏是我的代碼
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = @"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (@customer_id,@Employee_id,@Product_id,@[Date],@[Amount_Sold],@[Unit_Price],@[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("@customer_id", SqlDbType.Int);
Cmd.Parameters.Add("@Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("@Product_id", SqlDbType.Int);
//Cmd.Parameters.Add("@[Date]", SqlDbType.NVarChar);
Cmd.Parameters.Add("@[Date]", SqlDbType.Date);
Cmd.Parameters.Add("@[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("@[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("@Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["@customer_id"].Value = _customer_Id;
Cmd.Parameters["@Employee_id"].Value = _employee_Id;
Cmd.Parameters["@Product_id"].Value = _product_Id;
Cmd.Parameters["@[Date]"].Value = _date;
Cmd.Parameters["@[Amount_sold]"].Value = _amountSold;
Cmd.Parameters["@[Unit_Price]"].Value = _unitPrice;
Cmd.Parameters["@Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
我搜索的網站,但我找不到任何有用的東西或類似我的問題
我應該怎麼做?
您似乎試圖將列表插入到期望的整數參數中。如果你想要做的是基於列表的批量插入,你應該使用for循環中的i迭代器作爲列表的索引號。 'Cmd.Parameters [「@ Product_id」]。Value = _product_Id [i];'是涉及列表的一個示例。 –