.NET Programming With Me

Attaching SQL Server database using C#


private void AttachDatabase(string databaseName, string fileName, string loginName, string password)
{
     SqlConnection conn = new SqlConnection();
     SqlCommand cmd = new SqlCommand("", conn);


     conn.ConnectionString = "Data Source=" + serverName + ";Initial Catalog=Master;User Id = " + loginName + ";Password = " + password + "";


     cmd.CommandText = "exec sp_attach_single_file_db @dbname='" + databaseName + "',@physname='" + fileName + "'";


     try
     {
          conn.Open();
          cmd.ExecuteNonQuery();


          MessageBox.Show("Database Attached Successfully", "Attach Database");
     }
     catch (Exception)
     {
          //throw ex;
          MessageBox.Show("Could Not Attach Database \nLogin Failed for user " + loginName, "Attach Database");
     }
     finally
     {
          cmd.Dispose();
          conn.Dispose();
     }
}

No comments: