2016-09-18 2 views
-1
private void btnadd_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     conn.Open(); 
     string sql = ("Insert into tbl_books values NameOfBook = @book, Author [email protected], [email protected],[email protected],[email protected],[email protected]"); 
     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 블록으로 계속 들어갑니다.Sql 매개 변수의 오류

+1

쓸데없는 catch 블록은 좋은 방법이 아닙니다 쓰기. catch 블록을 가지고 적어도 예외 메시지 (IE : _catch (Exception ex) {MessageBox.Show (ex.Message);} _)를 표시하고 메시지 텍스트 – Steve

+0

을 알려주는 것이 SQL을 배우는 것보다 낫습니다. 자신의 구문/구조를 – Plutonix

+0

죄송합니다, 메신저 그냥 learning.thanks! – maklot

답변

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은 해커와 가장 당황스럽고 쉽게 수정할 수있는 보안 구멍을위한 가장 깔끔한 도구입니다!

참고 :는 자원을 절약하기 위해 사용 문에서 TRY 블록으로 CONN를 가져오고 그것을 포장 할 수 있습니다 :

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

도움에 감사드립니다! 그것은 작동합니다! 그것은 많은 것을 의미합니다! – maklot

+0

기꺼이 도와 드리겠습니다. 건배! –