Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

vb.net - ExecuteNonQuery: Connection property has not been initialized VB

Getting an error here not sure why its not opening the connection. Hoping someone can help me.

 Protected Sub Btn_Submit_Click(ByVal sender As System.Object, e As System.EventArgs) Handles Btn_Submit.Click
    Dim Sqlstr As String
    Dim con As SqlConnection
    Dim connectionString As String = "Data Source=DBTEST;Initial Catalog=Orders;Integrated Security=True"
    Dim cmdInsert As New SqlCommand(Sqlstr, con)
    Sqlstr = "insert into customers(FirstName,LastName,Email,Phone,Address,City,State,Zip) values (@FirstName,@LastName,@Email,@Phone,@Address,@City,@State,@Zip)"
    Try
        Using connection As New SqlConnection(connectionString)
            connection.Open()
            cmdInsert.Parameters.Add("@FirstName", Data.SqlDbType.NVarChar).Value = FirstName.Text()
            cmdInsert.Parameters.Add("@LastName", Data.SqlDbType.NVarChar).Value = LastName.Text
            cmdInsert.Parameters.Add("@Email", Data.SqlDbType.NVarChar).Value = Email.Text
            cmdInsert.Parameters.Add("@Phone", Data.SqlDbType.NChar).Value = Phone.Text
            cmdInsert.Parameters.Add("@Address", Data.SqlDbType.NVarChar).Value = Address.Text
            cmdInsert.Parameters.Add("@City", Data.SqlDbType.NVarChar).Value = City.Text
            cmdInsert.Parameters.Add("@State", Data.SqlDbType.NVarChar).Value = State.Text
            cmdInsert.Parameters.Add("@Zip", Data.SqlDbType.NChar).Value = Zip.Text
            cmdInsert.ExecuteNonQuery()
            connection.Close()
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two SqlConnection objects - one in Dim con As SqlConnection and then another in your using statement. Create the SqlCommand after the using statement and pass the connection in to the constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...