c#检测是否存在数据库(SQL SERVER)

private static bool CheckDatabaseExists( string databaseName)
{

        {
            string sqlCreateDBQuery;
            bool result = false;

            try
            {
                SqlConnection tmpConn = new SqlConnection(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=Example;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;");

                sqlCreateDBQuery = string.Format("SELECT database_id from sys.databases WHERE Name  = '{0}'", databaseName);
        
               using (tmpConn)
                {
                    using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
                    {
                        tmpConn.Open();

                        object resultObj = sqlCmd.ExecuteScalar();

                        int databaseID = 0;

                        if (resultObj != null)
                        {
                            int.TryParse(resultObj.ToString(), out databaseID);
                        }

                        tmpConn.Close();

                        result = (databaseID > 0);
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }
}
View Code

 

posted @ 2019-03-15 15:38  JackJu  阅读(3502)  评论(0编辑  收藏  举报