Share via


SqlConnection.ChangeDatabase(String) Method

Definition

Changes the current database for an open SqlConnection.

public:
 override void ChangeDatabase(System::String ^ database);
public override void ChangeDatabase (string database);
override this.ChangeDatabase : string -> unit
Public Overrides Sub ChangeDatabase (database As String)

Parameters

database
String

The name of the database to use instead of the current database.

Exceptions

The database name is not valid.

The connection is not open.

Cannot change the database.

Examples

The following example creates a SqlConnection and displays some of its read-only properties.

using Microsoft.Data.SqlClient;

class Program1
{
    static void Main()
    {
        string s = GetConnectionString();

        ChangeSqlDatabase(s);
        Console.ReadLine();
    }

    private static void ChangeSqlDatabase(string connectionString)
    {
        // Assumes connectionString represents a valid connection string
        // to the AdventureWorks sample database.
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
            Console.WriteLine("Database: {0}", connection.Database);

            connection.ChangeDatabase("Northwind");
            Console.WriteLine("Database: {0}", connection.Database);
        }
    }

    static private string GetConnectionString()
    {
        // To avoid storing the connection string in your code, 
        // you can retrieve it from a configuration file, using the 
        // System.Configuration.ConfigurationSettings.AppSettings property 
        return "Data Source=(local);Initial Catalog=AdventureWorks;"
            + "Integrated Security=SSPI;";
    }
}

Remarks

The value supplied in the database parameter must be a valid database name. The database parameter cannot contain a null value, an empty string, or a string with only blank characters.

Applies to