Skip to content

SqlConnection fails to connect to a new database if an attempt was made before the database existed #3875

@inoa-agrillo

Description

@inoa-agrillo

Describe the bug

When attempting to open a SqlConnection to a non-existent database, the expected exception is thrown. However, if the database is subsequently created (via a separate connection to master), and after that, a new SqlConnection is open to the original connection string it continues to fail with "Login failed" (Error 4060). I'm suspecting that the connection pool is reusing the previous connection.

Also, there is a time factor in this, if I break right after database creation the bug does not occur.

The exception that is throw in both occasion (before and after the database creation):

Microsoft.Data.SqlClient.SqlException: 'Database 'BugTestDB' already exists. Choose a different database name.'

To reproduce

using Microsoft.Data.SqlClient;

string cs = @"Data Source=.\SQLEXPRESS;Initial Catalog=BugTestDB;Integrated Security=True;TrustServerCertificate=True;";
string masterCs = @"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;TrustServerCertificate=True;";

// Expected Failure: Database does not exist yet
try { new SqlConnection(cs).Open(); }
catch { Console.WriteLine("Initial open failed (Expected)"); }

// Create the Database via master
using (var mConn = new SqlConnection(masterCs))
{
    mConn.Open();
    new SqlCommand("CREATE DATABASE BugTestDB", mConn).ExecuteNonQuery();
    Console.WriteLine("Database created");
}

// Connection should succeed now, but if it fails, the bug is reproduced
try
{
    new SqlConnection(cs).Open();
    Console.WriteLine("Bug NOT found.");
}
catch (Exception ex)
{
    Console.WriteLine($"Bug Found! Message: {ex.Message}");
}

Expected behavior

The second connection to BugTestDB should not fail

Further technical details

Microsoft.Data.SqlClient version: 6.1.3
.NET target: .NET 10
SQL Server version:
Microsoft SQL Server 2022 (RTM) - 16.0.1000.6 (X64)
Oct 8 2022 05:58:25
Copyright (C) 2022 Microsoft Corporation
Express Edition (64-bit) on Windows 10 Pro 10.0 (Build 26100: ) (Hypervisor)

Operating system: Microsoft Windows 11 Pro 10.0.26100 N/A Build 26100

Metadata

Metadata

Assignees

No one assigned

    Labels

    Repro Available ✔️Issues that are reproducible with repro provided.

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions