2014-09-22 66 views
0

我有一個表格,它有三列; ID,姓氏和名字更新/添加表中的行

即時消息試圖做的是做一個按鈕,可以添加一個新的行,另一個更新現有的聯繫人到這張表。我覺得我很接近,但有些東西只是沒有工作。我有一個工作正常的刪除方法,但我試圖做更新方法的方式是基本上刪除聯繫人,然後添加一個新的。它正在做的是刪除聯繫人,然後不添加任何其他內容。

這裏是我的addContact方法

 public int addContact(Contacts newContact) 
    { 

     MySqlConnection conn = null; 
     if (newContact != null) 
     { 
      try 
      { 
       conn = new MySqlConnection(); 
       conn.Open(); 

       MySqlCommand cmd = new MySqlCommand(); 
       cmd.Connection = conn; 
       cmd.CommandText = "insert into contacts (id, surname, last_name) values (@id, @surname, @firstName)"; 

       cmd.Prepare(); 

       cmd.Parameters.AddWithValue("@id", newContact.contactID); 
       cmd.Parameters.AddWithValue("@surname", newContact.surname); 
       cmd.Parameters.AddWithValue("@firstName", newContact.first_name); 
       cmd.ExecuteNonQuery(); 

       return (int)cmd.LastInsertedId; 
      } 
      catch (MySqlException ex) 
      { 
       Console.WriteLine("Error: {0}", ex.ToString()); 

      } 
      finally 
      { 
       if (conn != null) 
       { 
        conn.Close(); 
       } 

      } 

     } 
     return -1; 
    } 

而且我認爲主要的問題是不正確的即時通訊的方法。這裏是應該更新列表框中選擇的當前聯繫人的按鈕。

 private void button2_Click(object sender, EventArgs e) 
    { 
     Contacts currentContact = (Contacts)listBox1.SelectedItem; 
     contactMan.removeContact(currentContact.contactID); 
     Contacts testInsertContact = new Contacts(); 

     testInsertContact.surname = textBox2.Text; 
     testInsertContact.first_name = textBox3.Text; 
     testInsertContact.contactID = contactMan.addContact(testInsertContact); 
     reloadContacts(); 
    } 

任何幫助表示讚賞感謝


嗯,我通過提出一個新的項目,基本上重寫相同的代碼固定它。不知道爲什麼,但問題是它沒有正確連接到數據庫,並且無論出於何種原因它現在都可以正常工作。

+0

之前'MySqlCommand'有一個叫做'LastInsertedId'財產? – 2014-09-22 06:17:41

回答

0
cmd.CommandText = "insert into contacts (id, surname, last_name) values (@id, @surname, @firstName)"; 

寫這行只是

cmd.ExecuteNonQuery();