Sie sind auf Seite 1von 7

Para crear el backup necesitamos los siguientes espacios de nombres, ademas del servidor de datos, la base de datos, el nombre

del backup. creamos un proyecto como aparece en la imagen.

Imports System.Text Imports System.Data.SqlClient

El boton examinar nos permite seleccionar una carpeta donde crearemos el backup.

Private Sub btnExaminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExaminar.Click Dim Directorio As New FolderBrowserDialog If Directorio.ShowDialog = Windows.Forms.DialogResult.OK Then Me.txtDirPathBackup.Text = Directorio.SelectedPath

End If End Sub

Una vez ingresamos el nombre del servidor de datos, la base de datos, la ruta donde se guardar el archivo .bak del backup que haremos y la descripcion del backup damos click en el boton crear backup. En el evento click del mismo evaluaremos la informacion requerida, para que se vea mejor pueden agregar un errorprovider.

Private Sub btnBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackup.Click If cmbServidor.Text <> "" Then If Me.cboBaseDatos.Text <> "" Then If txtDirPathBackup.Text <> "" Then If txtNom_Backup.Text <> "" Then If txtDescrip_Backup.Text <> "" Then If crear_backup() = True Then MessageBox.Show("Backup creado satisfactoriamnete", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Error al crear el Backup", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End If Else MessageBox.Show("Ingrese una descripcion del Backup", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else MessageBox.Show("Ingrese el nombre del Backup", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else

MessageBox.Show("Seleccione la ruta donde se creara el Backup", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else MessageBox.Show("Seleccione la Base de Datos", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If Else MessageBox.Show("Ingrese el Nombre del Servidor de Datos SQL", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If End Sub

Una vez ingresamos los datos requeridos llamaremos la funcion backup(), la cual nos permite configurar un SqlConnectionStringBuilder para configurar la conexion, asi mismo como un StringBuilder para ingresar la sentencia del backup que ejecutaremos para hacer el backup.

Private Function crear_backup() As Boolean Dim conecsb As New SqlConnectionStringBuilder conecsb.DataSource = Me.cmbServidor.Text conecsb.InitialCatalog = "master" conecsb.IntegratedSecurity = True If txtDirPathBackup.Text.Length <> 3 Then txtDirPathBackup.Text = txtDirPathBackup.Text + "\" + txtNom_Backup.Text + ".bak" Else txtDirPathBackup.Text = txtDirPathBackup.Text + txtNom_Backup.Text + ".bak" End If Using con As New SqlConnection(conecsb.ConnectionString) Try con.Open() Dim sCmd As New StringBuilder sCmd.Append("BACKUP DATABASE [" + cboBaseDatos.Text + "] TO DISK = N" + txtDirPathBackup.Text + " ") sCmd.Append("WITH DESCRIPTION = N" + txtDescrip_Backup.Text + ", NOFORMAT, NOINIT, ")

sCmd.Append("NAME = N" + txtNom_Backup.Text + ", SKIP, NOREWIND, NOUNLOAD, STATS = 10") Dim cmd As New SqlCommand(sCmd.ToString, con) cmd.ExecuteNonQuery() crear_backup = True Catch ex As Exception crear_backup = False MessageBox.Show(ex.Message) Finally con.Close() End Try End Using End Function

Una vez se ejecuta satisfactoriamente el backup vemos que, en la ubicacion donde decidimos guardar el backup, aparece nuestro archivo .bak con el nombre que le dimos.

Restaurar una base de datos de SQL Server desde cdigo (VB)

'----------------------------------------------------------------------------' Restaurar una copia de una base de SQL Server (10/Ene/08) ' Ejemplo para restaurar una copia de seguridad de SQL Server 2005 ' ' Guillermo 'guille' Som, 2008 '-----------------------------------------------------------------------------

Option Strict On

Imports System Imports Microsoft.VisualBasic Imports System.Windows.Forms

Imports System.Data.SqlClient

Public Class Form1

Private Sub btnRestore_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRestore.Click Me.btnRestore.Enabled = False Me.btnRestore.Text = "Restaurando..." Me.btnRestore.Refresh()

Dim sBackup As String = "RESTORE DATABASE " & Me.txtBase.Text & _ " FROM DISK = '" & Me.txtBackup.Text & "'" & _ " WITH REPLACE"

Dim csb As New SqlConnectionStringBuilder csb.DataSource = Me.txtServidor.Text ' Es mejor abrir la conexin con la base Master csb.InitialCatalog = "master" csb.IntegratedSecurity = True

Using con As New SqlConnection(csb.ConnectionString) Try con.Open()

Dim cmdBackUp As New SqlCommand(sBackup, con) cmdBackUp.ExecuteNonQuery() MessageBox.Show("Se ha restaurado la copia de la base de datos.", _ "Restaurar base de datos", _ MessageBoxButtons.OK, MessageBoxIcon.Information)

con.Close() Catch ex As Exception MessageBox.Show(ex.Message, _

"Error al restaurar la base de datos", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using

Me.btnRestore.Text = "Restaurar copia" Me.btnRestore.Enabled = True Me.btnRestore.Refresh()

End Sub End Class

Script Para Restaurar Base de Datos Desde Unidad O Carpeta de Red Cuando utilizamos la interfaz de Sql Server, parece ser que es imposible restaurar una base de datos si es que no est en el disco duro local. Pero eso no es cierto, el problema es que slo puede hacerse con un script como el siguiente: RESTORE DATABASE DatabaseNameHere FROM DISK='\\server_name\folder\filename.bak' WITH REPLACE

hola bueno estoy haciendo una facturacion mi problema es como aumento automaticamente el numero de la factura me sale error create table n_factura (id_factura varchar(10)primary key) create procedure sp_nfactura as select * from n_factura where id_factura = (Select max(id_factura)+1 from n_factura) exec sp_nfactura go create procedure sp_addfactura @id_factura varchar(10) as insert into n_factura (id_factura) values (@id_factura)

insert into n_factura values ('00000') go //me sale error en vb 2008 Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32). Public Sub llenarserie() con.Open() cmd = New SqlCommand("sp_nfactura", con) cmd.CommandType = CommandType.StoredProcedure Dim da As New SqlDataAdapter(cmd) Dim ds As New DataSet da.Fill(ds, "sp_nfactura") Me.dgw2.DataSource = ds Me.dgw2.DataMember = "sp_nfactura" txtcolerrativo.Text = Format(((dgw2.Rows(0).Cells(0).Value Mod 10000) + 1), "0000") txtserie.Text = Format(((dgw2.Rows(0).Cells(0).Value / 10000)), "0000") serie = Format(((dgw2.Rows(0).Cells(0).Value) + 1), "000000") con.Close()

create procedure sp_codigo_factura as begin select max(id_factura) + 1 from n_factura end * luego creas otro procedimiento donde ya coga el valor creado y mostrado en tu diiseo create procedure sp_nfactura @codigo varchar(10) as begin insert into n_factura(id_factura) values('00000' & @codigo) end

Das könnte Ihnen auch gefallen