conexiÓn de base de datos utilizando visual basic 6 con ingreso

15
CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6.0 Y MICROSOFT ACCESS PARTE 1: CONEXIÓN A LA BASE DE DATOS, INGRESO Y CREACIÓN DE USUARIOS Utilización del control ADO en Visual Basic 6.0 Para activar este control se debe se agregar el siguiente componente: Clic derecho en la barra de controles (General) Luego escogemos la opción Microsoft ADO Data Control 6.0 (OLEDB) y pulsamos en el botón aceptar. Utilización del control DTPicker en Visual basic 6.0 Clic derecho en la barra de controles (General) Luego escogemos la opción Microsoft Windows Common Controls-2.6.0 (SP4) y pulsamos en el botón aceptar. Utilización del control DataGrid en Visual basic 6.0 Clic derecho en la barra de controles (General) Luego escogemos la opción Microsoft DataGrid Controls 6.0 (OLEDB) y pulsamos en el botón aceptar. Creación de un proyecto para la conexión de base de datos utilizando el control ADO. PRIMERO ABRIR VISUAL BASIC 6.0 Crear 7 formularios STANDAR, un formulario MDI y 2 módulos STANDAR. En los 7 formularios cambiamos en la ventana de propiedades las siguientes opciones: Form1: Nombre= frmcaratula BorderStyle=None StarUpPosition=CenterScreen Width=7065 Height=4335 Form2 : Nombre= frmingreso BorderStyle=None

Upload: luis-lalon

Post on 16-Apr-2015

37 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6.0 Y MICROSOFT ACCESS

PARTE 1: CONEXIÓN A LA BASE DE DATOS, INGRESO Y CREACIÓN DE USUARIOS

Utilización del control ADO en Visual Basic 6.0

Para activar este control se debe se agregar el siguiente componente:

Clic derecho en la barra de controles (General) Luego escogemos la opción Microsoft ADO Data Control 6.0 (OLEDB) y pulsamos en el botón aceptar.

Utilización del control DTPicker en Visual basic 6.0

Clic derecho en la barra de controles (General) Luego escogemos la opción Microsoft Windows Common Controls-2.6.0 (SP4) y pulsamos en el botón

aceptar.

Utilización del control DataGrid en Visual basic 6.0

Clic derecho en la barra de controles (General) Luego escogemos la opción Microsoft DataGrid Controls 6.0 (OLEDB) y pulsamos en el botón aceptar.

Creación de un proyecto para la conexión de base de datos utilizando el control ADO.

PRIMERO ABRIR VISUAL BASIC 6.0

Crear 7 formularios STANDAR, un formulario MDI y 2 módulos STANDAR.

En los 7 formularios cambiamos en la ventana de propiedades las siguientes opciones: Form1:

Nombre= frmcaratula BorderStyle=None StarUpPosition=CenterScreen Width=7065 Height=4335

Form2 : Nombre= frmingreso BorderStyle=None StarUpPosition=CenterScreen Width= 5625 Height= 3075

Form3 : Nombre= frmcrear BorderStyle=None Width= 14460

Page 2: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

Height= 7890 MDIChild=TRUE

Form4 : Nombre= frmmodificar BorderStyle=None Width= 14460 Height= 7890 MDIChild=TRUE

Form5 : Nombre= frmeliminar BorderStyle=None Width= 14460 Height= 7890 MDIChild=TRUE

Form6 : Nombre= frmbuscar BorderStyle=None Width= 10530 Height= 6405 MDIChild=TRUE

Form7 : Nombre= frmacerca BorderStyle=None Width= 7680 Height= 4635

FormMDI : Nombre= mdiprincipal Caption=Sistema de Usuarios WindowState= Maximized

Module1 : Nombre= moduledeclare

Module2 : Nombre= modulesentences

Page 3: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

Luego en el formulario frmcaratula ponemos los siguientes controles: Insertar 4 labels, un Timer como se muestra en la figura.

En todos los labels cambiamos en la ventana de propiedades las siguientes opciones:

Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

En el Timer cambiamos en la ventana de propiedades las siguientes opciones:

Nombre =tmrinicio Interval=3000

Luego abrimos la ventana de programación del tmrinicio y escribimos el siguiente código:

Private Sub tmrinicio_Timer()trminicio.Enabled = Falsefrmingreso.ShowUnload MeEnd Sub

Page 4: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

En los módulos creados vamos a escribir el siguiente código:

Antes de hacer esto necesitamos realizar lo siguiente:

En la barra de menús escogemos proyecto, luego referencias damos un clic se abra una ventana en la cual seleccionamos Microsoft ActiveX Data Objects 2.1 Library, lo cual nos permitirá declarar variables de tipo ADODB para manipular la base de datos una vez seleccionada damos en aceptar y listo.

Ahora abrimos el moduledeclare y escribimos lo siguiente: (la variable base servirá para la conexión a la base de datos y la variable Rsusuario servirá para el acceso a la tabla de la base de datos)

Global base As New ADODB.Connection Global Rsusuario As New ADODB.Recordset

Ahora abrimos el modulesentences y escribimos lo siguiente:

Esto nos permitirá realizar la conexión a la base de datos creada en Acces.

Sub main()With base .CursorLocation = adUseClient .Open "aquí va la cadena de conexión que se genera con el control Adodc visto en la clase anterior" End WithEnd Sub

Esto nos permitira verificar si la tabla de la base de datos esta abierta, si es así la cerraremos y la abriremos nuevamente.

Sub usuario()With Rsusuario If .State = 1 Then .Close .Open "select * from Usuario", base, adOpenStatic, adLockOptimisticEnd WithEnd Sub

Luego en el formulario frmingreso ponemos los siguientes controles: Insertar 2 labels, 2 Commandbutton, y 2 Textbox como se muestra en la figura.

Page 5: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

En los textbox cambiamos en la ventana de propiedades las siguientes opciones:

Text1 Nombre=txtid Height= 375 Width= 2535

Text2 Nombre=txtclave Height= 375 Width=2535 PasswordChar=*

En los CommandButton cambiamos en la ventana de propiedades las siguientes opciones:

commandButton1 nombre= cmdingresar caption=Ingresar width=1335 Height=495

commandButton2 nombre= cmdcancelar caption= Cancelar width= 1335 Height= 495

En los Label cambiamos en la ventana de propiedades las siguientes opciones:

Label1 caption= Id del Usuario Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label2 caption= Contraseña Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Page 6: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

Abrimos la ventana de programación para proceder a ingresar el siguiente código en los commandbutton:

Private Sub cmdingresar_Click()If txtid.Text = "" ThenMsgBox "Por favor ingrese el Nombre de Usuario", vbInformation, "Aviso"txtid.SetFocusExit SubEnd If

If txtClave.Text = "" ThenMsgBox "Por favor ingrese su Contraseña", vbInformation, "Aviso"txtClave.SetFocusExit SubEnd If

With Rsusuario .Requery 'actualiza la tabla de la base de datos .Find "id='" & Trim(txtid.Text) & "'" If .EOF Then MsgBox "Usuario Incorrecto", vbInformation, "Aviso" txtid.Text = "" txtid.SetFocus Exit Sub Else If !clave = Trim(txtClave.Text) Then MsgBox "Registro Satisfactorio", vbInformation, "Aviso" mdiprincipal.Show Unload Me Else MsgBox "Contraseña Incorrecta", vbInformation, "Aviso" txtClave.Text = "" txtClave.SetFocus Exit Sub End If End IfEnd WithEnd Sub

Private Sub cmdCancelar_Click()If MsgBox("Esta seguro que desea cancelar", vbInformation + vbYesNo, "Salir") = vbYes Then MsgBox "Gracias por Utilizar la Aplicación", vbInformation, "Aviso" EndEnd IfEnd Sub

Private Sub Form_Load()main

Page 7: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

usuarioEnd SubLuego en el formulario mdiprincipal creamos los siguientes menús como se muestra en la figura:

Para realizar estas operaciones nos dirigimos a la barra de menús y escogemos herramientas y luego escogemos editor de menús.

Page 8: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

Los nombres de los menús son:

mnuproyecto mnuusuarios mnucrear mnumodificar mnueliminar mnubuscar mnusalir mnuacerca

En el caption de cada uno de los menús vamos a poner lo siguiente:

Proyecto Usuarios Crear Modificar Eliminar Buscar Salir Acerca de..

Luego abrimos la ventana de programación para ingresar el siguiente código:

Private Sub MDIForm_QueryUnload(Cancel As Integer, UnloadMode As Integer)If MsgBox("Esta seguro que desea cerrar la aplicación", vbInformation + vbYesNo, "Cerrar") = vbYes Then MsgBox "Gracias por utilizar la Aplicacion", vbInformation, "Gracias" base.Close frmingreso.Show Unload MeElse Cancel = 1End IfEnd Sub

Private Sub mnuacerca_Click()mnuproyecto.Enabled = Falsefrmacerca.ShowEnd Sub

Private Sub mnubuscar_Click()mnucrear.Enabled = Falsemnuacerca.Enabled = Falsemnumodificar.Enabled = Falsemnueliminar.Enabled = Falsemnusalir.Enabled = False

Page 9: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

frmbuscar.ShowEnd Sub

Private Sub mnucrear_Click()mnuacerca.Enabled = Falsemnumodificar.Enabled = Falsemnueliminar.Enabled = Falsemnusalir.Enabled = Falsemnubuscar.Enabled = Falsefrmcrearusuario.ShowEnd Sub

Private Sub mnueliminar_Click()mnuacerca.Enabled = Falsemnumodificar.Enabled = Falsemnucrear.Enabled = Falsemnusalir.Enabled = Falsemnubuscar.Enabled = Falsefrmeliminarusuario.ShowEnd Sub

Private Sub mnumodificar_Click()mnuacerca.Enabled = Falsemnueliminar.Enabled = Falsemnucrear.Enabled = Falsemnusalir.Enabled = Falsemnubuscar.Enabled = Falsefrmmodificar.ShowEnd Sub

Private Sub mnusalir_Click() Unload MeEnd Sub

Sub activar() mnuproyecto.Enabled = True mnuusuarios.Enabled = True mnuacerca.Enabled = True mnueliminar.Enabled = True mnucrear.Enabled = True mnusalir.Enabled = True mnubuscar.Enabled = True mnumodificar.Enabled = TrueEnd Sub

Luego en el formulario frmcrear ponemos los siguientes controles: Insertar 8 labels, 2 Commandbutton, 6 Textbox y un DTPicker como se muestra en la figura.

Page 10: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

En los

Label cambiamos en la ventana de propiedades las siguientes opciones:

Label1 caption= Id del Usuario Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label2 caption= Contraseña Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label3 caption= Nombre Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label4 caption= Apellido Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Page 11: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

Label5 caption= Dirección Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label6 caption= Teléfono Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label7 caption= Fecha Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:14

Label8 caption= Creación de Usuarios Autosize=true BackStyle=Transparent Border style=None Font= fuente: MS Sans Serif; Estilo de fuente:Negrita; Tamaño:24

En los textbox cambiamos en la ventana de propiedades las siguientes opciones:

Text1 Nombre=txtid Height= 375 Width= 2535

Text2 Nombre=txtclave Height= 375 Width=2535 PasswordChar=*

Text3 Nombre=txtnombre Height= 327.236 Width= 2433.646

Text4

Page 12: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

Nombre=txtapellido Height= 327.236 Width= 2433.646

Text5 Nombre=direccion Height= 327.236 Width= 2433.646

Text6 Nombre=txttelefono Height= 327.236 Width= 2433.646

En el DTPicker1 cambiamos en la ventana de propiedades las siguientes opciones:

Nombre:DTPFecha Height= 327.236 Width= 1267.29

En los CommandButton cambiamos en la ventana de propiedades las siguientes opciones:

commandButton1 nombre= cmdcrear caption=Crear width= 998.131 Height= 431.951

commandButton2 nombre= cmdcancelar caption= Cancelar width= 998.131 Height= 431.951

En el DataGrid1 cambiamos en la ventana de propiedades las siguientes opciones:

Nombre: gridusuarios Caption: Lista de Usuarios Height= 1793.252 Width= 10508.42

Abrimos la ventana de programación para proceder a ingresar el siguiente código en los commandbutton:

Private Sub cmdCrear_Click()With Rsusuario .Requery

Page 13: CONEXIÓN DE BASE DE DATOS UTILIZANDO VISUAL BASIC 6 CON INGRESO

.AddNew !id = txtId.Text !clave = txtClave.Text !nombre = txtNombre !apellido = txtApellido !direccion = txtDireccion !telefono = txtTelefono !fecha = DTPFecha.Value .Update .Requery limpiarEnd WithEnd SubPrivate Sub Form_Load()

usuarioSet Gridusuarios.DataSource = tablafrmcrear.Top = Screen.Height / 2 - frmcrear.Height / 2frmcrear.Left = Screen.Width / 2 - frmcrear.Width / 2tabla.RequeryDTPFecha.Value = Date

End SubSub limpiar()

txtId.Text = ""txtClave.Text = ""txtNombre.Text = ""txtApellido.Text = ""txtDireccion.Text = ""txtTelefono.Text = ""DTPFecha.Value = DatetxtId.SetFocus

End Sub

Private Sub cmdCerrar_Click()If MsgBox("Esta seguro que desea salir", vbInformation + vbYesNo, "Salir") = vbYes Then Unload Me mdiprincipal.activarEnd IfEnd Sub