【问题标题】:Error with Sql ParametersSql 参数错误
【发布时间】:2016-09-18 12:55:53
【问题描述】:
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");
    }
}

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

【问题讨论】:

  • 写一个无用的 catch 块不是一个好习惯。如果你真的想要一个 catch 块,至少显示异常消息(IE: catch(Exception ex) { MessageBox.Show(ex.Message); } )并告诉我们消息文本跨度>
  • 学习 SQL 比自己编写语法/结构更好
  • 对不起,我只是在学习。谢谢!

标签: c# mysql parameters


【解决方案1】:

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

【讨论】:

  • 很高兴为您提供帮助 - 我们都去过那里。干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-26
相关资源
最近更新 更多