简体   繁体   中英

Updating/adding Rows in a table

I have a table that has three columns; ID, surname and first_name

What im trying to do is make a button that can add a new row, and another to update an existing contact to this table. I think im pretty close but there's something that just isnt working. I have a remove method which works fine, but the way im trying to do the update method is basically remove the contact then add a new one. What it's doing is removing the contact then not adding anything else.

Here's my addContact method

        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;
    }

And I think the main problem is that im the method incorrectly. Here's the button that should update that current contact selected in the listbox.

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

Any help is appreciated thanks


Well I fixed it by making a new project and basically rewriting the same code. No idea why but the problem was that it wasnt connecting to the database correctly and it works now for whatever reason.

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

请在

cmd.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM