簡體   English   中英

我如何使用 Dapper 為我的 sql 語句提供文本框值?

[英]how do i supply textbox values to my sql statement using Dapper?

兩次單擊按鈕的錯誤消息是:

附加信息:System.Windows.Controls.TextBox類型的成員Id不能作為參數值

    private void Button_Click(object sender, RoutedEventArgs e)

    {

        var connection = new SqlConnection(sqlConnectionString);

        Student student = new Student();

        connection.Open();
        
        var affectedRows = connection.Execute("Delete from Student Where Id = @Id", new { Id = txtStudentID });

            connection.Close();

            //return affectedRows;
    }











    private void Button_Click_1(object sender, RoutedEventArgs e)

    {
        var connection = new SqlConnection(sqlConnectionString);

        Student student = new Student();

        var affectedRows = connection.Execute("Update Student set Name = @Name, Marks = @Marks Where Id = @Id", new { Id = txtStudentID, Name = txtName.Text, Marks = txtMarks.Text });

        connection.Close();

    }  

您需要將文本框內的文本作為參數值發送,而不是文本框本身

connection.Execute(
  "Delete from Student Where Id = @Id", 
  new { Id = txtStudentID.Text }
//                       ^^^^^
);

最好不要讓 SQL Server 做數據轉換。 如果數據庫中的ID列是一個integer,在C#這邊解析字符串為integer:

connection.Execute(
  "Delete from Student Where Id = @Id", 
   new { Id = int.Parse(txtStudentID.Text) }
);

或者使用NumbericUpDown控件就不用擔心解析失敗(只能輸入數字)

connection.Execute(
  "Delete from Student Where Id = @Id", 
  new { Id = (int)nudStudentID.Value }
);

同樣,如果 ID 是一個 Guid,解析它。

更新查詢的建議相同 - 您在名稱和標記上有.Text (它是數字?請參閱上面的解析建議),但在 ID 上沒有; 可能是復制粘貼錯誤


其他建議:

您應該編寫using var來創建連接。 你不需要做一個新的學生。 Dapper 將打開/關閉已關閉的連接。 它將使您打開的連接保持打開狀態。 您不使用受影響的行,因此不需要捕獲它:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    using var connection = new SqlConnection(sqlConnectionString);

    connection.Execute(
        "Update Student set Name = @Name, Marks = @Marks Where Id = @Id", 
        new { 
          Id = int.Parse(txtStudentID.Text), 
          Name = txtName.Text, 
          Marks = double.Parse(txtMarks.Text)
        }
    );

}  

txtStudentID 是控件嗎? 如果是這樣,您應該使用 txtStudentID 的 Text 屬性。 如果它是數字數據類型,那么您可以嘗試 to.ToString() 它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM