2016-01-23 101 views
0

我試圖將數據插入到我的數據庫,當我按下按鈕它應該得到完成,但它不會我不能將數據插入我的數據庫

我想從我的最後一層在我的查詢某處

這裏是我的代碼

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

    } 

我想不出它在我的問題是

+0

你的問題是你有沒有錯誤處理 – amdixon

+0

添加_INT記錄= Cmd.ExecuteNonQuery()檢索元素; _然後用一個消息來顯示記錄變量。它應該是1,如果記錄已被插入,否則爲零。此外,該連接字符串文本是重複的。這只是一個錯字嗎? – Steve

+1

順便說一下,你用MySql TAG標記了這個,但是這似乎是來自連接字符串的SQL Server數據庫以及SqlConnection等Sql Server特定類的用法......那麼正確的數據庫是什麼呢? – Steve

回答

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(); 
} 
相關問題