我无法将数据插入我的数据库

时间:2016-01-23 10:00:03

标签: c# sql-server database winforms

我试图将数据插入到我的数据库中,当我按下按钮时它应该完成但是它不会

我想这是我在查询

中的最后一层

这是我的代码

   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();
            }
        }

    } 

我无法弄明白我的问题在哪里

1 个答案:

答案 0 :(得分:0)

问题是由您为参数设置的值引起的 您应该使用索引器从列表而不是整个列表中检索元素

// These doesn't change inside the loop, so set it once for all...
Cmd.Parameters["@customer_id"].Value = _customer_Id;
Cmd.Parameters["@Employee_id"].Value = _employee_Id;
Cmd.Parameters["@Date"].Value = _date;

for (int i = 0; i < RecordToAdd; i++)
{
    Cmd.Parameters["@Product_id"].Value = _product_Id[i];
    Cmd.Parameters["@Amount_sold"].Value = _amountSold[i];
    Cmd.Parameters["@Unit_Price"].Value = _unitPrice[i];
    Cmd.Parameters["@Total_Price"].Value = _totalPrice[i];
    Cmd.ExecuteNonQuery();
}
相关问题