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

后端 未结 4 1661
傲寒
傲寒 2021-01-12 00:25

I\'m creating a database using SQL Server Management Objects.

I wrote the following method to generate a database:

public static void CreateClientDat         


        
相关标签:
4条回答
  • 2021-01-12 00:27

    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.

    0 讨论(0)
  • 2021-01-12 00:29

    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.

    0 讨论(0)
  • 2021-01-12 00:39

    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

    0 讨论(0)
  • 2021-01-12 00:45

    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.

    0 讨论(0)
提交回复
热议问题