2010-03-09 98 views
0

我創建了一個使用SQL Server數據庫作爲後端的ASP.Net項目。我顯示以下錯誤。如何解決這個問題?SQL Server 2005中使用ASP.Net的問題

===============編碼

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 

=========錯誤消息============

ExecuteNonQuery: Connection property has not been initialized. 

回答

3

當你創建一個SqlCommand,它需要與連接相關聯:

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

次嘗試是,下面的代碼正確地處理任何非託管資源,連接已正確初始化:

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

+1。這是我做這件事的方式。我在上面回答時很懶惰。希望你會得到接受的答案。 – 2010-03-09 07:11:30

+0

不,再次出現同樣的錯誤,如何解決這個問題 – user246160 2010-03-09 10:19:54

+0

@megala你用上面提供的代碼替換了上面的代碼嗎?如果沒有,請做到這一點,然後再試一次。另外,如果再次失敗,請發佈完整的代碼和錯誤消息。 – 2010-03-09 15:22:19