1 year ago

#389158

test-img

Charlotte

SqlCommand not inserting into table

This code seems like it should work, but simply doesn't. I've tried it various ways (with & without SqlDataAdapter)

  1. I have both the mdf and xsd selected as "Copy if newer" currently, and have also tried never, and copy always.
  2. No errors are thrown when inserted, however if I try to insert a second time, the error

Violation of PRIMARY KEY constraint 'PK_owners'. Cannot insert duplicate key in object 'dbo.owners'. The duplicate key value is (Test). The statement has been terminated.

is returned, as if the data is actually in the table.

  1. I do have another table & form that does work (not inserts) It is a login table with data I manually inserted (SQL) at the time of table creation, the SQL select statements on that form work perfectly fine (also involve text boxes)
Private Sub btnInsertOwner_Click(sender As Object, e As EventArgs) Handles btnInsertOwner.Click

        Dim db As String = Path.Combine(Directory.GetCurrentDirectory(), "VBvetProject.mdf")

        Dim conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\VBvetProject.mdf;Integrated Security=True;")

        Using cmd As New SqlCommand("INSERT INTO owners VALUES (@fullname,@email,@phone,@dob)", conn)

            cmd.Parameters.AddWithValue("@fullname", txtOwnerFullName.Text)
            cmd.Parameters.AddWithValue("@email", txtOwnerEmail.Text)
            cmd.Parameters.AddWithValue("@phone", txtOwnerPhone.Text)
            cmd.Parameters.AddWithValue("@dob", txtOwnerDoB.Text)
            Dim adapter As New SqlDataAdapter(cmd)

            conn.Open()
            cmd.ExecuteNonQuery()
            Dim dt As New DataTable()
            adapter.Update(dt)
            conn.Close()
        End Using

        MessageBox.Show("New owner created!")

    End Sub

After attempting to insert a new record from the win form, I check it with a SQL select, and nothing returns (I also expand the table's data through Visual Studio, this is also still null.)

Here is a snip of the table and values:

enter image description here

I'm honestly at a loss here and could use any help figuring out what I'm doing wrong, this has been such a hair puller.

No matter how many ways I've tried changing the code, the connections, it just doesn't seem to work.

vb.net

visual-studio

winforms

tsql

0 Answers

Your Answer

Accepted video resources