ChangeDatabase
Connection.ChangeDatabase(String databaseName
);
Changes the current database used by the connection. This database is then used for all subsequent commands. This method corresponds to SQL Server’s USE command. In order to invoke this method, the connection must be open.
String
databaseName
The name of the new database to attach to (e.g.,
“Northwind”). A provider-specific
exception such as SqlException
is thrown if this
database doesn’t exist in the data source.
The following code opens a connection and executes two commands. The first command uses the Northwind database; the second uses the pubs database.
string connectionString = "Data Source=localhost;" + "Initial Catalog=Northwind;Integrated Security=SSPI"; string SQL1 = "UPDATE Categories SET Description='Coffee and tea' " + "WHERE CategoryName='Beverages'"; string SQL2 = "UPDATE Titles SET Title='The Busy Executive' " + "WHERE Title_Id='BU1032'"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmdA = new SqlCommand(SQL1, con); SqlCommand cmdB = new SqlCommand(SQL2, con); int rowsAffected; try { con.Open(); // Execute the first command using the Northwind database. rowsAffected = cmdA.ExecuteNonQuery(); // Execute the second command using the pubs database. con.ChangeDatabase("pubs"); rowsAffected += cmdB.ExecuteNonQuery(); } finally { con.Close(); }