2013-04-06 60 views
1

美好的一天。請告訴我
爲什麼我在將光標放在cmd變量上時收到錯誤消息「聲明期望」。我該怎麼辦?! ..代碼如下所示:聲明期望

Imports System.Data.Sqlclient 
Imports System.Configuration 

Partial Class _Default 
    Inherits Page 
    Private Shared Connectionstr As String ="DataSource=localhost;initialCatalog=Orders;Integrated Security=true" 
    Dim conn As SqlConnection = New SqlConnection(Connectionstr) 
    Dim cmd As SqlCommand = conn.CreateCommand() 
    cmd.CommandText="SELECT * FROM dbo.Customers" 
End Class 
+0

你應該怎麼做?你想做什麼_? – Oded 2013-04-06 11:11:59

回答

1

您試圖在屬性,函數或方法外使用變量命令。最起碼,嘗試在方法(子)包裹的命令執行與所述數據所需的操作:

偏類_Default 繼承頁面

Private Sub DoSomethingWithCustomers() 
    Dim conn As SqlConnection = New SqlConnection(Connectionstr) 
    Dim cmd As SqlCommand = conn.CreateCommand() 
    cmd.CommandText = "SELECT * FROM dbo.Customers" 

    conn.Open() 
    Dim dr = cmd.ExecuteReader() 
    ' Do something with the data returned . . . 
    ' ... 
    ' Now Cleanup: 
    conn.Close() 
    cmd.Dispose() 
    conn.Dispose() 
End Sub 

以上可以通過包裝數據來改善在使用塊訪問對象,其處理非託管資源的妥善處置你:

Private Sub DoSomethingBetterWithCustomers() 
    Dim SQL As String = "SELECT * FROM dbo.Customers" 
    Using conn As New SqlConnection(Connectionstr) 
     Using cmd As New SqlCommand(SQL, conn) 
      conn.Open() 
      Dim dr = cmd.ExecuteReader() 
      ' Do something with the data returned 
      ' . . . 
      dr.Close() 
     End Using ' Using Block takes carre of Disposing SqlCommand 
    End Using ' Using Block takes care of Closing and Disposing Connection 
End Sub 

除此之外,就很難知道什麼,準確地說,你想與您的代碼做的,所以上面的兩個例子真的,基本的和一般的。

相關問題