Sql参数错误

本文关键字:错误 参数 Sql | 更新日期: 2023-09-27 18:07:22

private void btnadd_Click(object sender, EventArgs e)
{
    try
    {
        conn.Open();
        string sql = ("Insert into tbl_books values NameOfBook = @book, Author =@author, Publisher=@publisher,YearPublished=@year,Category=@category,ISBN=@isbn");
        MySqlCommand sda = new MySqlCommand(sql,conn);
        sda.Parameters.AddWithValue("@book", txtbook.Text);
        sda.Parameters.AddWithValue("@author", txtauthor.Text);
        sda.Parameters.AddWithValue("@publisher", txtpublisher.Text);
        sda.Parameters.AddWithValue("@year", txtyear.Text);
        sda.Parameters.AddWithValue("@category", cmbcategory.Text);
        sda.Parameters.AddWithValue("@isbn", txtisbn.Text);
        sda.ExecuteNonQuery();
        conn.Close();
        MessageBox.Show("Item has been added");
        showlv("Select * from tbl_books", lvbooks);  
    }
    catch (Exception)
    {
        MessageBox.Show("Cannot Add Item");
    }
}

代码有什么问题?它继续进入接住块。

Sql参数错误

你的SQL一团糟。试一试:

  try
{
    conn.Open();
    string sql = "Insert into tbl_books (NameOfBook,Author,Publisher,YearPublished,Category,ISBN) values (@book,@author,@publisher,@year,@category,@isbn)";
    MySqlCommand sda = new MySqlCommand(sql,conn);
    sda.Parameters.AddWithValue("@book", txtbook.Text);
    sda.Parameters.AddWithValue("@author", txtauthor.Text);
    sda.Parameters.AddWithValue("@publisher", txtpublisher.Text);
    sda.Parameters.AddWithValue("@year", txtyear.Text);
    sda.Parameters.AddWithValue("@category", cmbcategory.Text);
    sda.Parameters.AddWithValue("@isbn", txtisbn.Text);
    sda.ExecuteNonQuery();
    conn.Close();
    MessageBox.Show("Item has been added");
    showlv("Select * from tbl_books", lvbooks);  
}

谢谢你花时间学习参数化。内联SQL是黑客最成熟的工具,也是最尴尬和最容易修复的安全漏洞!

注意:你可能想把你的conn放到TRY块中,并把它包装在USING语句中以节省资源:

  using(SqlConnection conn = getMyConnection())
  {
     conn.Open();
     //blah
     conn.Close();
  }