Hola amigos como estan espero que bien..
En este post les compartire un articulo de como hacer backup y Restore de base de datos en sql
desde visual estudio 2022 en c#.
2. Codigo fuente. Tab backup
3. Codigo fuente. Tab Restore
En este post les compartire un articulo de como hacer backup y Restore de base de datos en sql
desde visual estudio 2022 en c#.
- Primero diseñamos nuestro formulario como en la imagen.
//nuestro
conexion
SqlConnection cn = new
SqlConnection(ConfigurationManager.ConnectionStrings["tu conexion"].ConnectionString);
//código para
button backup
private void
button3_Click(object sender,
EventArgs e)
{
string cmfarma = cn.Database.ToString();
try
{
if (textBox2.Text == string.Empty)
{
MessageBox.Show("Por favor ingrese la ubicación del archivo de
respaldo");
}
else
{
string cmd = "BACKUP DATABASE [" + cmfarma + "] TO DISK='" +
textBox2.Text + "\\" + "cmfarma" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using (SqlCommand command = new SqlCommand(cmd, cn))
{
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
command.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Backup Creado Correctamente");
button3.Enabled = false;
}
}
}
catch
{
}
}
//código para
button ubicacion
private void
button4_Click(object sender,
EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox2.Text =
dlg.SelectedPath;
button3.Enabled = true;
}
}
3. Codigo fuente. Tab Restore
//código para
button ubicacion
private void
button1_Click(object sender,
EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "SQL SERVER database backup files|*.bak";
dlg.Title = "Database restore";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.FileName;
button2.Enabled = true;
}
}
//código para
button Restore
private void
button2_Click(object sender,
EventArgs e)
{
string database = cn.Database.ToString();
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, cn);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE
[" + database + "] FROM
DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, cn);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, cn);
bu4.ExecuteNonQuery();
MessageBox.Show("Restauración de la base de datos hecha exitosamente");
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
//Bueno eso es todo espero ayudarles.
dudas y sugerencias dejanos tu mensaje en los comentario gracias..




