2

I'm trying to Update and Insert records in a MySQL database, I can do both in separate buttons but I want to do both queries from a single button. I want to do something like: If the ID (which is primary key) = Something then update, else insert, but I can't figure out what I can base that off. Ill include some of my code below.

INSERTING

Private Function saveCustomer()
    Dim command As MySqlCommand = Nothing
    Dim query As String = "INSERT INTO contacts (first_name, surname, house_number, street, suburb, state, phone, mobile, work, email, notes) VALUES (@first_name, @surname, @housenumber, @street, @suburb, @state, @phone, @mobile, @work, @email, @notes)"
    Try
        If connection.State = ConnectionState.Closed Then
            connection.Open()

        End If
        command = New MySqlCommand(query, connection)
        command.Parameters.AddWithValue("@first_name", txtFirstName.Text)
        command.Parameters.AddWithValue("@surname", txtSurname.Text)
        command.Parameters.AddWithValue("@housenumber", txtHouseNo.Text)
        command.Parameters.AddWithValue("@street", txtStreet.Text)
        command.Parameters.AddWithValue("@suburb", txtSuburb.Text)
        command.Parameters.AddWithValue("@state", cboState.Text)
        command.Parameters.AddWithValue("@phone", txtPhone.Text)
        command.Parameters.AddWithValue("@mobile", txtMobile.Text)
        command.Parameters.AddWithValue("@work", txtWork.Text)
        command.Parameters.AddWithValue("@email", txtEmail.Text)
        command.Parameters.AddWithValue("@notes", txtNotes.Text)
        command.ExecuteNonQuery()
        MessageBox.Show("Contact Saved Sucessfully")
        Return True
    Catch ex As MySqlException
        Return False
    Finally
        connection.Close()
        command.Dispose()
    End Try

End Function

UPDATING

Private Sub updateContact()
    Dim command As MySqlCommand = Nothing
    Dim query As String = "UPDATE contacts SET first_name=@first_name, surname=@surname, house_number=@housenumber, street=@street, suburb=@suburb, state=@state, phone=@phone, mobile=@mobile, work=@work, email=@email, notes=@notes WHERE id= '" & ListView1.FocusedItem.SubItems(1).Text & "'"

    Try
        connection.Open()

        command = New MySqlCommand(query, connection)
        command.Parameters.AddWithValue("@first_name", txtFirstName.Text)
        command.Parameters.AddWithValue("@surname", txtSurname.Text)
        command.Parameters.AddWithValue("@housenumber", txtHouseNo.Text)
        command.Parameters.AddWithValue("@street", txtStreet.Text)
        command.Parameters.AddWithValue("@suburb", txtSuburb.Text)
        command.Parameters.AddWithValue("@state", cboState.Text)
        command.Parameters.AddWithValue("@phone", txtPhone.Text)
        command.Parameters.AddWithValue("@mobile", txtMobile.Text)
        command.Parameters.AddWithValue("@work", txtWork.Text)
        command.Parameters.AddWithValue("@email", txtEmail.Text)
        command.Parameters.AddWithValue("@notes", txtNotes.Text)
        command.ExecuteNonQuery()

        MessageBox.Show("Contact Updated Successfully")

    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        connection.Close()
        command.Dispose()

    End Try
End Sub

AND THIS POPULATES MY LISTVIEW FROM THE DATABASE

Private Sub loadcontacts() 
    Dim command As MySqlCommand = Nothing
    Dim listquery As String = "SELECT * FROM contacts ORDER BY id"
    Dim reader As MySqlDataReader = Nothing

    Try
        If connection.State = ConnectionState.Closed Then
            connection.Open()
        End If

        command = New MySqlCommand(listquery, connection)
        reader = command.ExecuteReader()
        command.CommandText = listquery

        With ListView1
            .Columns.Add("Name", 220, HorizontalAlignment.Left)

        End With


        While reader.Read
            Dim ls As New ListViewItem(reader.Item("first_name").ToString() & " " & reader.Item("surname").ToString)
            ls.SubItems.Add(reader.Item("id").ToString)
            ListView1.Items.Add(ls)

        End While

    Catch ex As MySqlException
    Finally
        connection.Close()
        command.Dispose()
    End Try

End Sub

UPDATE

I still can't work it out, I'm cheating by including a text box and having it read the id, then i tell it to save ifs it's empty. I would prefer to do it correctly so if anyone can chime in I'd appreciate it.

0

1 Answer 1

1

It has been ages since I worked with VB so I'm sure the syntax is a bit off. Anyone feel free to edit as needed.

In your button click event handler

If LEN(ListView1.FocusedItem.SubItems(1).Text) > 0 Then
    updateContact()
Else
    saveCustomer()
End If

Note I assume here that the ID is set in

ListView1.FocusedItem.SubItems(1).Text

and that, if the record being edited is new, this will evaluate to an empty string. If that assumption is wrong, you'll have to share how you know whether or not an ID is available for the insert/update.

UPDATE

it crashes if I don't select a record before I try to create a new record

In that case, rather than checking

ListView1.FocusedItem.SubItems(1).Text

you should check whether ListView1 has any focused items.

If ListView1.FocusedItem <> NULL Then
    updateContact()
Else
    saveCustomer()
End If
Sign up to request clarification or add additional context in comments.

3 Comments

Code updates but doesn't save, and it crashes if I don't select a record before I try to create a new record
Ok first of all it tells me that NULL is no longer supported so I guess you used to use it in an older version haha. So Instead I put: If ListView1.FocusedItem.Text <> "" Then updateContact() Else SaveCustomer() which gives me the same results, only updates.
The MSDN documentation states that null will be returned if there is no focused item. I'm not sure how that translates into VB.Net msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.