viernes, 17 de agosto de 2007

Insertar Registros con Procedimientos almacenados

Siguiendo con la Instruccion Insert ahora veremos como hacerlo usando ahora procedimientos almacenados, para ello solo crearemos el Procedimiento Inserta_alumno con el siguiente codigo:

create procedure inserta_alumno
(
@nom varchar(50),
@grado tinyint,
@seccion char(1),
@sancion smallint
)
as
insert into alumnos(Nombre,Grado,Seccion,IdSancion)
values(@nom,@grado,@seccion,@sancion)

la estructura de la tabla es la que sigue

Y Como el formulario es el que sigue


Y el codigo necesario que invoca a el procedimiento almacenado es el que sigue


Imports System
Imports System.Data
Imports System.Data.SqlClient


Public Class Form2
Public cn As New SqlConnection("data source=familia;initial catalog=Colegio;integrated security=true;")
Public ds As New DataSet
Public cmd As SqlCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'validamos los textbox
If TextBox1.Text.Trim = "" Then
MessageBox.Show("Ingrese Nombre")
End If
If TextBox2.Text.Trim = "" Then
MessageBox.Show("Ingrese Grado")
End If
If TextBox3.Text.Trim = "" Then
MessageBox.Show("Ingrese Seccion")
End If
If TextBox4.Text.Trim = "" Then
MessageBox.Show("Ingrese sancion")
End If
cmd = New SqlCommand
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "inserta_alumno"
cmd.Connection = cn
Dim da As New SqlDataAdapter
da.InsertCommand = cmd
Dim nom As New SqlParameter("@nom", SqlDbType.VarChar, 50)
Dim grado As New SqlParameter("@grado", SqlDbType.TinyInt, 1)
Dim seccion As New SqlParameter("@seccion", SqlDbType.Char, 1)
Dim sancion As New SqlParameter("@sancion", SqlDbType.SmallInt, 2)
da.InsertCommand.Parameters.Add(nom)
da.InsertCommand.Parameters(0).Value = TextBox1.Text
da.InsertCommand.Parameters.Add(grado)
da.InsertCommand.Parameters(1).Value = TextBox2.Text
da.InsertCommand.Parameters.Add(seccion)
da.InsertCommand.Parameters(2).Value = TextBox3.Text
da.InsertCommand.Parameters.Add(sancion)
da.InsertCommand.Parameters(3).Value = TextBox4.Text
Try
Using cn
cn.Open()
da.InsertCommand.ExecuteNonQuery()
MessageBox.Show("registro Grabado Correctamente ")
da.Dispose()
cmd.Dispose()
End Using

Catch ex As Exception
MessageBox.Show(ex.Message.ToString)

End Try

End Sub
End Class

Como Vemos es identico al ejemplo anterior, bueno hasta la Proxima

Luis Ramirez G
Net Developer Specialist
DCE2005 2 estrellas


No hay comentarios: