2017-05-27 171 views
1

'輸入字符串格式不正確'。errro將數據插入數據庫時​​

我想用C#將數據插入到MYSQL數據庫,但我得到的是說

輸入字符串的不正確的格式錯誤消息。 (ExecuteNonQuery)時出現此錯誤。

public void Register_Cutomer_Orders() 
    { 
     string ConnStr = ConfigurationManager.ConnectionStrings["ConnSet"].ConnectionString; 
     string cmdstr = @"INSERT INTO `shopsorders` 
             (`order_id`, 
             `Customers_customer_id`, 
             `Employees_employee_id`, 
             `Shops_shop_id`, 
             `total`, 
             `date`) 
           VALUES 
             (@P_order_id, 
             @P_Customers_customer_id, 
             @P_Employees_employee_id, 
             @P_Shops_shop_id, 
             @P_total, 
             @P_date)"; 
     try 
     { 
      using (MySqlConnection conn = new MySqlConnection(ConnStr)) 
      using (MySqlCommand cmd = new MySqlCommand(cmdstr, conn)) 
      { 

       conn.Open(); 
       cmd.CommandType = CommandType.Text; 
       cmd.CommandText = cmdstr; 
      foreach (DataGridViewRow item in dGVShop.Rows) 
      { 
       cmd.Parameters.Clear(); 

       cmd.Parameters.Add("@P_order_id", MySqlDbType.Int32).Value = null; 
       cmd.Parameters.Add("@P_Customers_customer_id", MySqlDbType.Int32).Value = Convert.ToInt32(TB_Shop_ReservNum.Text); 
       cmd.Parameters.Add("@P_Employees_employee_id", MySqlDbType.Int32).Value = 1; 
       cmd.Parameters.Add("@P_Shops_shop_id", MySqlDbType.Int32).Value = Convert.ToInt32(cbShop_Name.SelectedValue); 
       cmd.Parameters.Add("@P_total", MySqlDbType.Double).Value = Convert.ToDouble(tb_Shop_Total.Text); 
       cmd.Parameters.Add("@P_date", MySqlDbType.DateTime).Value = "sysdate()"; 

       cmd.ExecuteNonQuery(); 

      } 
       conn.Close(); 
      } 
    } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 

}

+1

嘗試的日期參數 – Turo

+0

一個真正的日期。如果你總是希望在'date'然後把SYSDATE在SELECT中,不要打擾使用它的參數。 – Crowcoder

回答

2

sysdate()是不是可以轉換爲日期的字符串。如果你的意思是發送當前時間,使用DateTime.UtcNow

cmd.Parameters.AddWithValue("@P_date", MySqlDbType.DateTime).Value = DateTime.UtcNow; 

當執行隱式轉換,數據庫不執行字符串標記 - 它只是嘗試將其轉換爲所需要的類型。

也:@P_Customers_customer_id@P_Shops_shop_id@P_total都是數字,但給定的文本價值,這是一個非常糟糕的主意

1

AddWithValue的第二個參數是不是參數但該值的類型。

cmd.Parameters.AddWithValue("@P_Customers_customer_id", TB_Shop_ReservNum.Text); 

正如你所看到的,這仍然是非常弱的,因爲你傳遞一個字符串,並AddWithValue決定參數類型看接收到的輸入。

本博客文章解釋AddWithValue 的所有弱點Can we stop using AddWithValue already?

我更喜歡使用Add方法以這種方式

cmd.Parameters.Add("@P_Customers_customer_id", MySqlDbType.Int32).Value = Convert.ToInt32(TB_Shop_ReservNum.Text); 

最後,當你把這個字符串「SYSDATE()」,它會不能在系統日期解析,但在一個文字字符串中,顯然文本'sysdate()'不是日期。

在這種情況下,你建議立即進行刪除使用存儲過程,讓您的服務器上的系統日期或通過本地計算機DateTime.Now