美好的一天。请告诉我 将光标放在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 :(得分:1)
您正在尝试在Property,Function或Method外部使用变量命令。至少,尝试将命令包装在方法(Sub)中,该方法使用数据执行所需的操作:
Partial Class _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
通过将数据访问对象包装在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
除此之外,很难知道你正在尝试用你的代码做什么,所以上面的两个例子真的非常基本和一般。