0

I am trying to insert data to database, but getting error as ExecuteNonQuery: Connection property has not been initialized.

Everything seems ok with the connection.

Imports System.Data.SqlClient
Public Class crud1
    Private Sub Add_btn_Click(sender As Object, e As EventArgs) Handles Add_btn.Click
        Try
            Dim conn_ As New SqlConnection("Data Source=DESKTOP-VVM5A31;Initial Catalog=temp;Integrated Security=True")
            conn_.Open()
            Dim command As New SqlCommand("INSERT INTO STUDENT (student_name, student_age) VALUES (@NAME, @AGE)")
            command.Parameters.AddWithValue("@NAME", TXT_NAME.Text)
            command.Parameters.AddWithValue("@AGE", Convert.ToInt32(TXT_AGE.Text))
            command.ExecuteNonQuery()
            MsgBox("Record saved.", MsgBoxStyle.Information)
            conn_.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
End Class

Please see the image for the connection property.

enter image description here

1
  • 3
    You never attach your connection conn_ to your SqlCommand command to; as such you get an error that the connection wasn't initialised, as command.Connection hasn't been set. Ideally you should be using Using syntax too. See the answer here. Commented Mar 16, 2022 at 10:54

1 Answer 1

2

You are right taking into account that the command needs the connection open, before execute the command, and you are doing right.

But you are not telling to the command which is the connection to be used.

An easy way to do it would be something like this, before execute the command:

command.Connection = conn_
Sign up to request clarification or add additional context in comments.

1 Comment

That's not wrong but, under the circumstances, it would make more sense to pass the connection to the command constructor: Dim command As New SqlCommand("INSERT INTO STUDENT (student_name, student_age) VALUES (@NAME, @AGE)", conn_).

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.