How to check for the existence of a DB?

前端 未结 8 2229
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: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
    }
    

提交回复
热议问题