-1

I am trying to insert data into an existing Microsoft SQL Server 2014 table using VB.NET 2017. The code does not give me any errors, but it does not insert the record either. Right now I just want to get it to where it alters data, without worrying about user input. Any help is appreciated.

My guess is that it is not connecting to SQL Server properly.

Imports System.Data.SqlClient
Public Class Form2

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sqlstr As String
    Dim connectionString As String = "server=localhost;database= database1;Trusted_Connection=True;"
    sqlstr = "Insert into tblname (id, gender) VALUES ([5], ['Bob'])"
    Try
        Using connection As New SqlConnection(connectionString)
            connection.Open()
            Dim cmdInsert As New SqlCommand(sqlstr, connection)
            connection.Close()
        End Using
        MsgBox("anything")    'this is just to see if it even runs
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

4

After you create the SqlCommand, just call ExecuteNonQuery to run the SQL statement:

Dim cmdInsert As New SqlCommand(sqlstr, connection)
cmdInsert.ExecuteNonQuery()
connection.Close()

But note that the values in your INSERT statement should not be surrounded by brackets:

sqlstr = "Insert into tblname (id, gender) VALUES (5, 'Bob')"
Michael Liu
  • 52,147
  • 13
  • 117
  • 150