Tài liệu Changing the Database for an Open Connection - Pdf 87

[ Team LiB ]Recipe 1.18 Changing the Database for an Open Connection
Problem
You want to change the database that a connection uses without recreating the
connection.
Solution
Use the ChangeDatabase( ) method to change the database for a connection.
The sample code creates a Connection to the Northwind database using the SQL Server
.NET data provider. The connection is changed to use the pubs database. Finally the
connection is closed. The Database property of the SqlConnection object is displayed
throughout the sample for the different connection states.
The C# code is shown in Example 1-12
.
Example 1-12. File: ChangeDatabaseForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Text;
using System.Data;
using System.Data.SqlClient;

// . . .

StringBuilder result = new StringBuilder( );

// Create the connection accessing Northwind database.
SqlConnection conn = new SqlConnection(
ConfigurationSettings.AppSettings["Sql_ConnectString"]);
result.Append("Connection String:" + Environment.NewLine);

closed connection when it is opened.
When the Connection is closed after ChangeDatabase( ) is called, the database is reset to
that specified in the original connection string.

[ Team LiB ]


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status