elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  simple ejemplo ;) sql~visual
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: simple ejemplo ;) sql~visual  (Leído 2,387 veces)
_-Javier-_

Desconectado Desconectado

Mensajes: 18


凸 ◣_◢ ( Javier )◣_◢ 凸


Ver Perfil WWW
simple ejemplo ;) sql~visual
« en: 20 Enero 2011, 22:12 pm »

Bueno soy nuevo en este foro asi k aki les dejo algo ojala les interese
utilizamos sql server 2008 .creamos una nueva query y escribimos el siguiente codigo


Código
  1. GO
  2. USE master
  3. GO
  4. SET LANGUAGE spanish
  5. GO
  6. IF(DB_ID('ejemplo')IS NOT NULL)
  7. DROP DATABASE ejemplo
  8. GO
  9. CREATE DATABASE ejemplo
  10. GO
  11. USE ejemplo
  12. GO
  13. CREATE TABLE individuo
  14. (dni CHAR(8) PRIMARY KEY,
  15. apellidos VARCHAR(30) NOT NULL,
  16. nombre VARCHAR(30) NOT NULL,
  17. sexo CHAR(1) NOT NULL CHECK (sexo IN('M','F')),
  18. fecnac DATE NOT NULL,
  19. edad tinyint NOT NULL,
  20. salario money)
  21. GO
  22. CREATE proc registrar(@dni CHAR(8),
  23. @ape VARCHAR(30),
  24. @n VARCHAR(30),
  25. @s CHAR(1),
  26. @fn DATE,
  27. @e tinyint,
  28. @sueldo money,
  29. @msj VARCHAR(60)output)
  30. AS BEGIN
  31. IF(NOT EXISTS(SELECT * FROM individuo WHERE dni =@dni ))
  32. BEGIN
  33. INSERT INTO individuo VALUES(@dni,@ape,@n,@s,@fn,@e,@sueldo)
  34. SET @msj ='REGISTRADO'
  35. END
  36. ELSE
  37. --NO EXISTE UNA PERSONA CON EL MISMO DNI
  38. SET @msj ='DNI YA EXISTE'
  39. END
  40. GO
  41. CREATE proc modificar(@dni CHAR(8),
  42. @ape VARCHAR(30),
  43. @n VARCHAR(30),
  44. @s CHAR(1),
  45. @fn DATE,
  46. @e tinyint,
  47. @sueldo money,
  48. @msj VARCHAR(60)output)
  49. AS BEGIN
  50. IF(EXISTS(SELECT * FROM individuo WHERE dni =@dni ))
  51. BEGIN
  52. UPDATE individuo SET apellidos =@ape ,nombre =@n ,sexo =@s ,fecnac =@fn ,edad =@e ,salario =@sueldo WHERE dni =@dni
  53. SET @msj ='Datos modificados'
  54. END
  55. ELSE
  56. SET @msj ='DNI no existe'
  57. END
  58. GO
  59. CREATE proc eliminar(@dni CHAR(8),@msj VARCHAR(60)output)
  60. AS BEGIN
  61. IF(EXISTS(SELECT * FROM individuo WHERE dni =@dni ))
  62. BEGIN
  63. DELETE FROM individuo WHERE dni =@dni
  64. SET @msj ='Datos eliminados'
  65. END
  66. ELSE
  67. SET @msj ='DNI no existe'
  68. END
  69.  

2_despues de haber hecho el code en sql pasamos a visual
2.1_creamos un nuevo proyecto de tipo solucion(otros tipo de proyecto)
http://img143.imageshack.us/i/53607601.jpg/

2.2_siguiendo nos vamos a herramientas (proyectos y soluciones-general-activamos mostrar solucion siempre)
http://img828.imageshack.us/i/21239949.jpg/

2.3_le damos anticlik ala solucion y agregar nuevo proyecto de tipo biblioteca de clases.(le pondremos por nombre biblioteca)por defecto aparecera una clase ya creada(utilizaremos mas adelante)
http://img203.imageshack.us/i/85722103.jpg/
http://img573.imageshack.us/i/95876910.jpg/

2.4_hacemos lo mismo del paso 2.3 pero esta ves creamos una aplicacion de windows forms llamada formularios
http://img713.imageshack.us/i/38902831.jpg/

2.5_le damos anticlik a biblioteca (agregar ->modulo)y aplicamos el siguiente code


Código
  1. Imports System.Data
  2. Imports System.Data.SqlClient
  3. Module Module1
  4.    Public con As New SqlConnection("Data Source=.;DataBase=ejemplo;Integrated Security=true")
  5.    Public Sub abrir()
  6.        If con.State = 0 Then con.Open()
  7.    End Sub
  8.    Public Sub cerrar()
  9.        If con.State = 1 Then con.Close()
  10.    End Sub
  11. End Module
  12.  

2.6_ahora le damos anticlik ala solucion y propiedades escogemos como proyecto de inicio formularios
http://img200.imageshack.us/i/82265367.jpg/

2.7_le agregamos referencia (anticlik a formularios-agregar referencia.proyectos-boblioteca(unika opcion))y aceptar
http://img256.imageshack.us/i/20827082.jpg/

2.8_entramos a clase 1 escribiremos el code para manejar los procedimientos (registrar-modificar-eliminar)de la BD


Código
  1.  
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4. Public Class Class1
  5.    Private m_dni, m_ape, m_n, m_s As String
  6.    Private m_fn As Date
  7.    Private m_edad As Integer
  8.    Private m_sueldo As Decimal
  9.    Public Property dni() As String
  10.        Get
  11.            Return m_dni
  12.        End Get
  13.        Set(ByVal value As String)
  14.            m_dni = value
  15.        End Set
  16.    End Property
  17.    Public Property ape() As String
  18.        Get
  19.            Return m_ape
  20.        End Get
  21.        Set(ByVal value As String)
  22.            m_ape = value
  23.        End Set
  24.    End Property
  25.    Public Property n() As String
  26.        Get
  27.            Return m_n
  28.        End Get
  29.        Set(ByVal value As String)
  30.            m_n = value
  31.        End Set
  32.    End Property
  33.    Public Property s() As String
  34.        Get
  35.            Return m_s
  36.        End Get
  37.        Set(ByVal value As String)
  38.            m_s = value
  39.        End Set
  40.    End Property
  41.    Public Property fn() As Date
  42.        Get
  43.            Return m_fn
  44.        End Get
  45.        Set(ByVal value As Date)
  46.            m_fn = value
  47.        End Set
  48.    End Property
  49.    Public Property edad() As Integer
  50.        Get
  51.            Return m_edad
  52.        End Get
  53.        Set(ByVal value As Integer)
  54.            m_edad = value
  55.        End Set
  56.    End Property
  57.    Public Property sueldo() As Decimal
  58.        Get
  59.            Return m_sueldo
  60.        End Get
  61.        Set(ByVal value As Decimal)
  62.            m_sueldo = value
  63.        End Set
  64.    End Property
  65.    Public Function listado()
  66.        Dim dt As New DataTable
  67.        Dim da As SqlDataAdapter
  68.        Try
  69.            abrir()
  70.            da = New SqlDataAdapter("select *from individuo", con)
  71.            da.Fill(dt)
  72.        Catch ex As Exception : Throw ex
  73.        End Try
  74.        cerrar()
  75.        Return dt
  76.    End Function
  77.    Public Function registrar() As String
  78.        Dim msj As String
  79.        Dim cmd As SqlCommand
  80.        Try
  81.            '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est
  82.            abrir()
  83.            cmd = New SqlCommand("registrar", con)
  84.            cmd.CommandType = CommandType.StoredProcedure
  85.            With cmd.Parameters
  86.                cmd.Parameters.AddWithValue("@dni", dni)
  87.                cmd.Parameters.AddWithValue("@ape", ape)
  88.                cmd.Parameters.AddWithValue("@n", n)
  89.                cmd.Parameters.AddWithValue("@s", s)
  90.                cmd.Parameters.AddWithValue("@fn", fn)
  91.                cmd.Parameters.AddWithValue("@e", edad)
  92.                cmd.Parameters.AddWithValue("@sueldo", sueldo)
  93.                cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output
  94.                cmd.ExecuteNonQuery()
  95.                msj = cmd.Parameters("@msj").Value
  96.            End With
  97.        Catch ex As Exception : Throw ex
  98.        End Try
  99.        cerrar()
  100.        Return msj
  101.    End Function
  102.    Public Function modificar() As String
  103.        Dim msj As String
  104.        Dim cmd As SqlCommand
  105.        Try
  106.            '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est
  107.            abrir()
  108.            cmd = New SqlCommand("modificar", con)
  109.            cmd.CommandType = CommandType.StoredProcedure
  110.            With cmd.Parameters
  111.                cmd.Parameters.AddWithValue("@dni", dni)
  112.                cmd.Parameters.AddWithValue("@ape", ape)
  113.                cmd.Parameters.AddWithValue("@n", n)
  114.                cmd.Parameters.AddWithValue("@s", s)
  115.                cmd.Parameters.AddWithValue("@fn", fn)
  116.                cmd.Parameters.AddWithValue("@e", edad)
  117.                cmd.Parameters.AddWithValue("@sueldo", sueldo)
  118.                cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output
  119.                cmd.ExecuteNonQuery()
  120.                msj = cmd.Parameters("@msj").Value
  121.            End With
  122.        Catch ex As Exception : Throw ex
  123.        End Try
  124.        cerrar()
  125.        Return msj
  126.    End Function
  127.    Public Function eliminar() As String
  128.        Dim msj As String
  129.        Dim cmd As SqlCommand
  130.        Try
  131.            '@dni,@idt ,@ape,@nom,@sex,@fn,@fi,@fono,@est
  132.            abrir()
  133.            cmd = New SqlCommand("eliminar", con)
  134.            cmd.CommandType = CommandType.StoredProcedure
  135.            With cmd.Parameters
  136.                cmd.Parameters.AddWithValue("@dni", dni)
  137.                cmd.Parameters.Add("@msj", SqlDbType.VarChar, 30).Direction = ParameterDirection.Output
  138.                cmd.ExecuteNonQuery()
  139.                msj = cmd.Parameters("@msj").Value
  140.            End With
  141.        Catch ex As Exception : Throw ex
  142.        End Try
  143.        cerrar()
  144.        Return msj
  145.    End Function
  146. End Class

2.9 _despues de haber hecho lo anterior nos vamos al formulario(acomodar la interfaz)Y ESCRIBIMOS EL CODE
http://img41.imageshack.us/i/81843289.jpg/

Código
  1. Imports biblioteca
  2. Public Class Form1
  3.    Public p As New biblioteca.Class1
  4.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  5.        listado()
  6.        RadioButton1.Checked = True
  7.    End Sub
  8.    Sub listado()
  9.        Try
  10.            DataGridView1.DataSource = p.listado()
  11.        Catch ex As Exception : MessageBox.Show(ex.Message)
  12.        End Try
  13.    End Sub
  14.  
  15.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  16.        Try
  17.            p.dni = TextBox1.Text
  18.            p.ape = TextBox2.Text
  19.            p.n = TextBox3.Text
  20.            If RadioButton1.Checked = True Then
  21.                p.s = "M"
  22.            Else
  23.                p.s = "F"
  24.            End If
  25.            p.fn = DateTimePicker1.Value
  26.            p.edad = TextBox4.Text
  27.            p.sueldo = TextBox5.Text
  28.            MessageBox.Show(p.registrar())
  29.        Catch ex As Exception : MessageBox.Show(ex.Message)
  30.        End Try
  31.        listado()
  32.        limpiar()
  33.    End Sub
  34.    Sub limpiar()
  35.        TextBox1.Clear()
  36.        TextBox2.Clear()
  37.        TextBox3.Clear()
  38.        TextBox4.Clear()
  39.        TextBox1.ReadOnly = False
  40.        TextBox5.Clear()
  41.        DateTimePicker1.Value = Now
  42.        RadioButton1.Checked = True
  43.        TextBox1.Focus()
  44.    End Sub
  45.  
  46.    Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
  47.        Dim ed As Integer
  48.        ed = Now.Year - DateTimePicker1.Value.Year
  49.        TextBox4.Text = ed
  50.    End Sub
  51.  
  52.    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  53.        Try
  54.            p.dni = TextBox1.Text
  55.            p.ape = TextBox2.Text
  56.            p.n = TextBox3.Text
  57.            If RadioButton1.Checked = True Then
  58.                p.s = "M"
  59.            Else
  60.                p.s = "F"
  61.            End If
  62.            p.fn = DateTimePicker1.Value
  63.            p.edad = TextBox4.Text
  64.            p.sueldo = TextBox5.Text
  65.            MessageBox.Show(p.modificar())
  66.        Catch ex As Exception : MessageBox.Show(ex.Message)
  67.        End Try
  68.        listado()
  69.        limpiar()
  70.    End Sub
  71.  
  72.    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
  73.        Try
  74.            p.dni = TextBox1.Text    
  75.            MessageBox.Show(p.eliminar())
  76.        Catch ex As Exception : MessageBox.Show(ex.Message)
  77.        End Try
  78.        listado()
  79.        limpiar()
  80.    End Sub
  81.  
  82.    Private Sub DataGridView1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.Click
  83.        Try
  84.            Dim fila As Integer = DataGridView1.CurrentRow.Index
  85.            With DataGridView1.Rows(fila)
  86.                TextBox1.Text = .Cells(0).Value.ToString
  87.                TextBox2.Text = .Cells(1).Value.ToString
  88.                TextBox3.Text = .Cells(2).Value.ToString
  89.                If .Cells(3).Value.ToString = "M" Then
  90.                    RadioButton1.Checked = True
  91.                Else
  92.                    RadioButton2.Checked = True
  93.                End If
  94.                DateTimePicker1.Value = .Cells(4).Value.ToString
  95.                TextBox4.Text = .Cells(5).Value.ToString
  96.                TextBox5.Text = .Cells(6).Value.ToString
  97.            End With
  98.            TextBox1.ReadOnly = True
  99.        Catch ex As Exception : MessageBox.Show("fila sin datos")
  100.  
  101.        End Try
  102.    End Sub
  103. End Class
  104.  

nota: UTILIZAMOS PROCEDIMIENTOS ,Funciones,Parametros de salida(output)
PARA BUSCAR LOS DATOS SOLO DA CLIK EN CUALQUIERA CELDA .
PARA LIMPIAR LAS CAJAS AGREGA UN LINKLABEL (LE AGREGAS EL CODE(limpiar))

saludos : ojala les sirva


Nota del Moderador: Por favor, existe la etiqueta Code, la cual puedes usar sin ningún problema.Gracias.


« Última modificación: 22 Enero 2011, 16:30 pm por _-Javier-_ » En línea



Uploaded with ImageShack.us
rdzlcs


Desconectado Desconectado

Mensajes: 784


El cerebro, la experiencia y una pizca de suerte.


Ver Perfil
Re: simple ejemplo ;) sql~visual
« Respuesta #1 en: 21 Enero 2011, 00:52 am »

Usa el código para remarcar el código
Código:
Este
y esos colores dañan la vista, usa el negro o en su defecto el azul.
Arregla eso después miro los códigos.

SAludos


En línea

.:Snifer:.

Desconectado Desconectado

Mensajes: 74


Ver Perfil
Re: simple ejemplo ;) sql~visual
« Respuesta #2 en: 21 Enero 2011, 01:03 am »

Emm arreglo los codes por lo que vi es con procedimientos almacenados.. seria bueno que arregles mas las imagenes
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines