vb.net 预期声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15850131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaration Expected
提问by user2252020
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:
大家好。请告诉我
为什么将光标放在 cmd 变量上时会收到错误消息“Declaration Expected”。我该怎么办?!.. 代码如下:
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
回答by XIVSolutions
You are attempting to use the variable command outside a Property, Function, or Method. At the very least, try wrapping your command in a method (Sub) which performs the desired action with the data:
您正试图在属性、函数或方法之外使用变量命令。至少,尝试将您的命令包装在一个方法 (Sub) 中,该方法使用数据执行所需的操作:
Partial Class _Default Inherits Page
部分类_默认继承页面
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
The above can be improved by wrapping your data access objects in Using blocks, which handle proper disposal of unmanaged resources for you:
可以通过将数据访问对象包装在 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
Beyond that, it is difficult to know what, precisely, you are trying to do with your code, so the two examples above are really, really basic and general.
除此之外,很难确切地知道您想用代码做什么,因此上面的两个示例非常非常基本和通用。

