user246160
user246160

Reputation: 1397

Problem in SQL Server 2005 using ASP.Net

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.

Upvotes: 0

Views: 80

Answers (3)

Ricardo Sanchez
Ricardo Sanchez

Reputation: 6289

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();
    }
}

Upvotes: 1

Mitch Wheat
Mitch Wheat

Reputation: 300599

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

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

Upvotes: 3

hallie
hallie

Reputation: 2845

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

Upvotes: 0

Related Questions