Export (0) Print
Expand All

SqlConnection.Open Method

Opens a database connection with the property settings specified by the ConnectionString.

[Visual Basic]
Public Overridable Sub Open() Implements IDbConnection.Open
[C#]
public virtual void Open();
[C++]
public: virtual void Open();
[JScript]
public function Open();

Implements

IDbConnection.Open

Exceptions

Exception Type Condition
InvalidOperationException Cannot open a connection without specifying a data source or server.

or

The connection is already open.

SqlException A connection-level error occurred while opening the connection.

Remarks

The SqlConnection draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server.

Note   If the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose.
Note   If you specify a port number when trying to connect to an instance of SQL Server and using a protocol other than TCP/IP, the Open method fails.
Note   The .NET Framework Data Provider for SQL Server requires the Security permission with "Allows calls to unmanaged assemblies" enabled (SecurityPermission with SecurityPermissionFlag set to UnmanagedCode) to open a SqlConnection with SQL Debugging enabled.

Example

[Visual Basic, C#, C++] The following example creates a SqlConnection, opens it, displays some of its properties, then closes the connection.

[Visual Basic] 
Public Sub CreateSqlConnection(myConnString As String)
    Dim myConnection As New SqlConnection(myConnString)
    myConnection.Open()
    MessageBox.Show("ServerVersion: " & myConnection.ServerVersion & ControlChars.Cr & _
                    "State: " & myConnection.State.ToString())
    myConnection.Close()
End Sub 'CreateSqlConnection

[C#] 
public void CreateSqlConnection(string myConnString) 
 {
    SqlConnection myConnection = new SqlConnection(myConnString);
    myConnection.Open();
    MessageBox.Show("ServerVersion: " + myConnection.ServerVersion + 
                    "\nState: " + myConnection.State.ToString());
    myConnection.Close();
 }

[C++] 
public:
void CreateSqlConnection(String* myConnString) 
 {
    SqlConnection* myConnection = new SqlConnection(myConnString);
    myConnection->Open();
    MessageBox::Show(String::Format( S"ServerVersion: {0}\nState: {1}",
       myConnection->ServerVersion, __box(myConnection->State)));
    myConnection->Close();
 }

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

See Also

SqlConnection Class | SqlConnection Members | System.Data.SqlClient Namespace | Close

Show:
© 2014 Microsoft