1

Good day all. Please advise me
Why I got an error message "Declaration Expected" when put the cursor on cmd variable. What Should I do?! .. the code appears below:

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 
4

1 回答 1

1

您正试图在属性、函数或方法之外使用变量命令。至少,尝试将您的命令包装在一个方法(Sub)中,该方法对数据执行所需的操作:

部分类_默认继承页面

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

可以通过将数据访问对象包装在 Using 块中来改进上述情况,这些块可以为您正确处理非托管资源:

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

除此之外,很难确切地知道您要对代码做什么,因此上面的两个示例非常非常基本和通用。

于 2013-04-06T12:28:41.823 回答