How to check for the existence of a DB?

前端 未结 8 2200
Happy的楠姐
Happy的楠姐 2020-12-18 05:52

I am wondering if there is an elegant way to check for the existence of a DB? In brief, how do test the connection of a db connection string?

Thanks

相关标签:
8条回答
  • 2020-12-18 06:24

    Set the Initial Catalog=master in the connection string and execute:

    select count(*) from sysdatabases where name = @name
    

    with @name set to the name of the database.

    If you want to check the connection string as a whole (and not existence of an independent database), try connecting to it in a try/catch block.

    0 讨论(0)
  • 2020-12-18 06:28

    This is what worked for me to verify the existence of any Postgres database with C#:

    private bool chkDBExists(string connectionStr, string dbname)
    {
        using (NpgsqlConnection conn = new NpgsqlConnection(connectionStr))
        {
            using (NpgsqlCommand command = new NpgsqlCommand
                ($"SELECT DATNAME FROM pg_catalog.pg_database WHERE DATNAME = '{dbname}'", conn))
            {
                try
                {
                    conn.Open();
                    var i = command.ExecuteScalar();
                    conn.Close();
                    if (i.ToString().Equals(dbname)) //always 'true' (if it exists) or 'null' (if it doesn't)
                        return true;
                    else return false;
                }
                catch (Exception e) { return false; }
            }
        }
    }
    

    ** The if used in the try-catch statement could simply check if the return of the ExecuteScalar is null for non-existent DB and not-null if it exists.

    0 讨论(0)
  • 2020-12-18 06:33

    If you're using Entity Framework or have it available to you, you can simply call Database.Exists():

    if (Database.Exists(connectionString))
    {
        // do something
    }
    else
    {
        // do something else
    }
    
    0 讨论(0)
  • 2020-12-18 06:39

    Just try a DBConnection.Open() wrapped in a try block catching DBException.

    About as elegant a solution as you are going to find.

    0 讨论(0)
  • 2020-12-18 06:40

    You could just try connecting to it. If it throws an exception, then the connection string is bad in some way, either the database doesn't exist, the password is wrong, or something else.

    DbConnection db = new SqlConnection(connection_string);
    try
    {
        db.Open();
    }
    catch ( SqlException e )
    {
        // Cannot connect to database
    }
    
    0 讨论(0)
  • 2020-12-18 06:40

    you can get list of Database with below and check your db name:

    USE master
    GO  
    SELECT name, database_id, create_date  
    FROM sys.databases ;  
    GO
    
    0 讨论(0)
提交回复
热议问题