Operations on a SQL Server Database Connection


Opening a Connection

If you are "physically" connecting to a server or a database using the SQL Server Enterprise Manager or the SQL Query Analyzer, the steps we have described so far allow you to open the connection.

If you are creating the connection through the Data Link Properties to open the connection, you can click OK.

After creating a connection string, to apply it and actually establish the connection, you must call the SqlConnection.Open(). Its syntax is:

Public Overridable Sub Open() Implements IDbConnection.Open

As you can see, this method doesn't take any argument. The SqlConnection object that calls it is responsible to get the connection string ready. If the connection fails, the compiler would throw a SqlException exception. If connection string doesn't contain the computer attribute or the connection is already opened, the compiler would throw an InvalidOperationException exception.

Closing a Connection

After using a connection and getting the necessary information from it, you should terminate it. If you are working in SQL Server Enterprise Manager or the SQL Query Analyzer, to close the connection, you can simply close the window as an application.

If you are working in Microsoft Visual Studio .NET, to close a connection, right-click it and click Close Connection:

In this case, the Close Connection menu item would becomes disabled, indicating that the connection is not available. To re-establish it, you can simply right-click that connection and click Modify Connection.

If you are working from a SqlConnection object, to close a connection, you can call the SqlConnection.Close() method. Its syntax is:

Public Overridable Sub Close() Implements IDbConnection.Close

This method is simply called to close the current connection. While you should avoid calling the Open() method more than once if a connection is already opened, you can call the Close() method more than once.


Previous Copyright © 2005-2015, FunctionX Next