2013-04-06 75 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 

除此之外,就很难知道什么,准确地说,你想与您的代码做的,所以上面的两个例子真的,基本的和一般的。