views:

38

answers:

3

I created one ASP.Net project using SQL Server database as back end. I shows the following error. How to solve this?

===============Coding

Imports System.Data.SqlClient

Partial Class Default2

    Inherits System.Web.UI.Page

    Dim myConnection As SqlConnection


    Dim myCommand As SqlCommand
    Dim ra As Integer

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        myConnection = New SqlConnection("Data Source=JANANI-FF079747\SQLEXPRESS;Initial Catalog=new;Persist Security Info=True;User ID=sa;Password=janani") 'server=localhost;uid=sa;pwd=;database=pubs")

        myConnection.Open()

        myCommand = New SqlCommand("Insert into table3 values 'janani','jan'")

        ra = myCommand.ExecuteNonQuery() ========---> error is showing here

        MsgBox("New Row Inserted" & ra)

        myConnection.Close()

    End Sub

End Class 

=========Error Message============

ExecuteNonQuery: Connection property has not been initialized.
+3  A: 

When you create a SqlCommand, it needs to be associated with a connection:

myCommand = 
    New SqlCommand("Insert into table3 values 'janani','jan'", myConnection); 
Mitch Wheat
A: 
 myCommand = New SqlCommand("Insert into table3 values 'janani','jan'", myConnection)
hallie
+1  A: 

Try this, the following code properly disposes any unmanaged resources and the connection is properly initialized:

using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
    using (SqlCommand dataCommand = dataConnection.CreateCommand())
    {
        dataCommand.CommandText = "Insert into table3 values 'janani','jan'"

        dataConnection.Open();
        dataCommand.ExecuteNonQuery();
        dataConnection.Close();
    }
}
Ricardo
+1. This is the way I do it. I was lazy when I answered above. Hopefully you will get the accepted answer.
Mitch Wheat
no,the same error again come,how to solve this
@megala Did you replaced your code above with the one I provided? if not, please do that and try again. Also, post the entire code and error message if it fails again.
Ricardo