Can't immediately connect to newly-created SQL Server database

三世轮回 提交于 2019-12-01 03:53:54

A database that has just come online is not necessarily ready to accept connections. To identify when a database can accept connections, query the collation_name column of sys.databases or the Collation property of DATABASEPROPERTYEX. The database can accept connections when the database collation returns a non-null value.

The database name" requested by the login. The login failed. Login failed for user 'the user'

One thing to note here all is that the error message is surrounding security. How are you attempting to logon to the new database (i.e. what type of security is the connection string using for the new database connection)? If you are using SQL authentication you will need to issue sp_adduser to grant the login access to the database.

http://msdn.microsoft.com/en-us/library/ms181422.aspx

Robert Hegner

In my case it turned out that the problem is not that the newly created database is not ready. But the problem was that SqlConnection.Open() apparently used a failed cached connection, which then just returned the same error again.

When I call the static SqlConnection.ClearAllPools() method before I try to open the newly created database, it works fine!

See also this question.

You have to approach the database creation a little bit different. The code below handles the database creation correctly. Try it ;)

private void CreateDatabase(string databaseName)
{

    Microsoft.SqlServer.Management.Smo.Server sqlServer = 
            new Microsoft.SqlServer.Management.Smo.Server(_connection);

    Database createdDatabase = new Database();
    createdDatabase.Name = databaseName;
    createdDatabase.Parent = sqlServer;
    createdDatabase.Create();

}

In the code below, the _connection is a

Microsoft.SqlServer.Management.Smo.ServerConnection
object by the way.

[Edit] Modified the code so the exception is not swallowed anymore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!