La Web del Programador: Comunidad de Programadores
 
    Pregunta:  62075 - VB CON SQL SERVER
Autor:  Javier Herrera
Hola tengo el siguiente problema al hacer mi ABM de una tabla clientes, estoy intentando programar en 3 capas (usuario, reglas de negocio, datos). Este código lo tenia funcionando con DAO y una base de access. Ahora lo he intentado pasar a ADO con SQL Server y lee la base de datos pero no Actualiza ni da de Alta

Public Sub GuardarDatos()
If rs.BOF And rs.EOF Then
rs.AddNew
Else
' rs.edit '*****aqui no se que método usar para editar
End If
rs!NroCliente = ClienteEnUso.NroCliente
rs!Nombre = ClienteEnUso.Nombre
rs.Update
End Sub

Anteriormente he declarado estas variables en este modulo de clase , lee la tabla captura los datos en los textbox del formulario de la interfaz de usuario) pero cuando quiero actualizar no lo hace.

Private ClienteEnUso As TipoCliente
Private flgEsNuevo As Boolean
Private DB As New Connection
Private rs As New Recordset

Desde ya muchas gracias por contestar.
Saludos
Javier

  Respuesta:  David Enriquez
En un Modulo crear una funcion con el siguiente codigo

Function Conectar()
Dim provedor, servidor, database, Usuario, contraseña As String
provedor = "SQLOLEDB"
servidor = ServidorX
database = "BaseX"
usuario = "UsuarioX"
contraseña = "PasswordX"


Set oDb = New ADODB.Connection
With oDb
.Provider = provedor
.Properties("User ID").Value = Usuario
.Properties("Password").Value = contraseña
.Properties("Initial Catalog").Value = database
.Properties("Data Source").Value = servidor
End With

' oDb.Open
'Verifico la conexion, por si las dudas
If oDb.State <> adStateOpen Then
' MsgBox "No se puede generar la conexion SQL, verifique que los datos sean correctos", vbInformation
' Exit Sub
'Reabro la conexión
On Error Resume Next
oDb.Open
varx = oDb.State
If varx = 0 Then
MsgBox "Los datos de la conexion son incorrectos", vbCritical, "Error"
Bandera = 1
' Exit Sub
Else
Bandera = 0
End If
End If

End Function

***********Ya en tu form y en el boton Guardar iria esto:

Dim IDPer As Integer
Dim ApPat, ApMat, Nombres, Auxiliar1, Auxiliar2, Auxiliar3 As String

On Error Resume Next ' Inicializa el controlador de error.

If Bandera = 0 Then

ApPat = Text1.Text
ApMat = Text2.Text
Nombres = Text3.Text
Auxiliar1 = Text4.Text
Auxiliar2 = Text5.Text
Auxiliar3 = Text6.Text

If Nombres = "" Then
MsgBox "Debe ingresar por lo menos el nombre para dar de alta un usuario", vbCritical, EXE
Exit Sub
Else
'Hacer el proceso de Guardar nuevo registro
IDPer = Ultimo("PERSONAL", "ID_PERSONAL")

Campos = "ID_PERSONAL,APELLIDO1,APELLIDO2,NOMBRE,AUX1,AUX2,AUX3"
Registros = "" & IDPer & ",'" & ApPat & "','" & ApMat & "','" & Nombres & "'," _
& " '" & Auxiliar1 & "','" & Auxiliar2 & "','" & Auxiliar3 & "'"

SQLAddUser = "INSERT INTO PERSONAL" _
& " (" & Campos & ")VALUES" _
& " (" & Registros & ")"

oDb.Execute (SQLAddUser)

Text1.Text = Clear
Text2.Text = Clear
Text3.Text = Clear
Text4.Text = Clear
Text5.Text = Clear
Text6.Text = Clear

X = MuestraPersonal("PERSONAL", Grid)

MsgBox "Se ha registrado nuevo personal correctamente", vbInformation, EXE

End If

Else
Text1.Text = Clear
Text2.Text = Clear
Text3.Text = Clear
Text4.Text = Clear
Text5.Text = Clear
Text6.Text = Clear
Command1.Caption = "&Guardar"
Bandera = 0
Command2.Enabled = False
Text1.SetFocus
End If
Combo1.Text = Clear

Err.Clear
' Comprueba el error, después muestra un mensaje.
If Err.Number <> 0 Then
Msj = "Error # " & Str(Err.Number) & " fue generado por " _
& Err.Source & Chr(13) & Err.Description
MsgBox Msj, , "Error", Err.HelpFile, Err.HelpContext
End If

**************Y para actualizar iria esto

On Error Resume Next
'Previo a esto yo le puse un procedimiento que al hacer doble clic sobre un registro del Grid se me llenen los datos en
'los controles...mas abajo viene....
IdPerX = Grid.Text 'lo que tengan seleccionado en el grid se actualizara

ApPat = Text1.Text
ApMat = Text2.Text
Nombres = Text3.Text
Auxiliar1 = Text4.Text
Auxiliar2 = Text5.Text
Auxiliar3 = Text6.Text

If Nombres = "" Then
MsgBox "Debe ingresar por lo menos el nombre para dar de alta un usuario", vbCritical, EXE
Exit Sub
Else
End If
Campos = "ID_PERSONAL,APELLIDO1,APELLIDO2,NOMBRE,AUX1,AUX2,AUX3"
Registros = "" & IDPer & ",'" & ApPat & "','" & ApMat & "','" & Nombres & "'," _
& " '" & Auxiliar1 & "','" & Auxiliar2 & "','" & Auxiliar3 & "'"

If IdPerX <> "" Then
pregunta = MsgBox("¿Desea actualizar el registro seleccionado?", vbYesNo, EXE)
If pregunta = 6 Then
SQL = ""
SQL = "UPDATE PERSONAL SET APELLIDO1='" & ApPat & "',APELLIDO2='" & ApMat & "'," _
& " NOMBRE='" & Nombres & "',AUX1='" & Auxiliar1 & "',AUX2='" & Auxiliar2 & "'," _
& " AUX3='" & Auxiliar3 & "' WHERE ID_PERSONAL=" & IdPerX & ""
oDb.Execute (SQL)
MsgBox "El registro se ha Actualizado", vbInformation, EXE
Unload Me
Me.Show
Else
End If
Else
End If

Err.Clear
' Comprueba el error, después muestra un mensaje.
If Err.Number <> 0 Then
Msj = "Error # " & Str(Err.Number) & " fue generado por " _
& Err.Source & Chr(13) & Err.Description
MsgBox Msj, , "Error", Err.HelpFile, Err.HelpContext
End If


Procedimiento en el evento doble clic del Grid

Private Sub Grid_DblClick()

On Error Resume Next
Command2.Enabled = True
Command1.Caption = "Limpiar"
Bandera = 1
Text1.SetFocus
IdPerX = Grid.Text

SQL = ""
SQL = "SELECT * FROM PERSONAL WHERE ID_PERSONAL=" & IdPerX & ""

Set RST = Nothing
Set RST = New ADODB.Recordset
RST.CursorLocation = adUseClient

With RST
.ActiveConnection = oDb
.LockType = adLockOptimistic
.CursorType = adOpenDynamic
.Source = SQL
.Open
End With

ren = RST.RecordCount
If ren > 0 Then
With RST
Text1.Text = RST(1)
Text2.Text = RST(2)
Text3.Text = RST(3)
Text4.Text = RST(4)
Text5.Text = RST(5)
Text6.Text = RST(6)
End With
RST.Close
Else
'ENTRY1 = "" & vbTab & ""
End If

Err.Clear
' Comprueba el error, después muestra un mensaje.
If Err.Number <> 0 Then
Msj = "Error # " & Str(Err.Number) & " fue generado por " _
& Err.Source & Chr(13) & Err.Description
MsgBox Msj, , "Error", Err.HelpFile, Err.HelpContext
End If

End Sub

Espero te sirva saludos...