Ado.net SqlConnection Open方法

时间:2011-11-20 19:55:05

标签: vb.net ado.net sqlconnection

我正在学习ADO.NET但对我来说很难......我不明白为什么会遇到这个编译错误: 连接的“预期声明”。打开()。

我写这段代码

Imports System
Imports System.Data
Imports System.Data.SqlClient

Public Class Basics

    Dim connection As SqlConnection = DataConnection.GetConnectToSql

    ' Here the error: "Declaration expected"
    connection.Open()


End Class

Imports System.Data.SqlClient

Public Class DataConnection

    ' SQL Server Connection
    Dim connection As SqlConnection = DataConnection.GetConnectToSql

    ' SQL Server Connection with connectionString method
    Public Shared Function GetConnectToSql() As SqlConnection
        Dim connectionString As String =
            "Data Source=localhost\sqlexpress;Initial Catalog=Payables;" &
            "Integrated Security=True"
        Return New SqlConnection(connectionString)
    End Function

End Class

1 个答案:

答案 0 :(得分:2)

您正在尝试在方法或属性之外执行功能。

Imports System
Imports System.Data
Imports System.Data.SqlClient

Public Class Basics
    Private connection As SqlConnection = DataConnection.GetConnectToSql

    Public Sub Open()
        connection.Open()
    End Sub
End Class

Public Class DataConnection
    ' SQL Server Connection
    Private connection As SqlConnection = GetConnectToSql()

    ' SQL Server Connection with connectionString method
    Public Shared Function GetConnectToSql() As SqlConnection
        Dim connectionString As String = _
            "Data Source=localhost\sqlexpress;Initial Catalog=Payables;" & _
            "Integrated Security=True"
        Return New SqlConnection(connectionString)
    End Function
End Class