Science And Technology">
Nothing Special   »   [go: up one dir, main page]

Actividad VIII - Programación II

Descargar como docx, pdf o txt
Descargar como docx, pdf o txt
Está en la página 1de 11

UNIVERSIDAD ABIERTA PARA ADULTOS UAPA

Asignatura
Programación II

Tema
Actividad VIII

Participante
JONATHAN JOSE POLANCO
2019-02723

Facilitador
Diógenes Amaury Martínez

Santiago de los Caballeros


16/7/2020
1) Investiga y elabora un informe acerca de los procedimientos almacenados y muestra ejemplo
vinculados a C#

Un procedimiento almacenado es un conjunto de instrucciones de T-SQL que SQL Server compila, en un


único plan de ejecución, los llamados "store procedures" se encuentran almacenados en la base de datos,
los cuales pueden ser ejecutados en cualquier momento.

Se pueden emplear cuatro métodos para crear procedimientos almacenados, utilizando:

 El Transact-SQL (T-SQL).
 El Administrador Corporativo de SQL Server.
 El asistente para La Creación de Procedimientos Almacenados (Create Store Procedure Wizard).
 Los objetos de Administración distribuida de SQL (SQL Distributed Management Objects, SQL-
DMO).

Dentro de las características principales que ofrecen se destacan las siguientes.

Por su Rendimiento: al ser ejecutados por el motor de base de datos ofrecen un rendimiento inmejorable
ya que no es necesario transportar datos a ninguna parte. Cualquier proceso externo tiene una penalidad
de tiempo adicional dada por el transporte de datos

Por su Potencia: el lenguaje para procedimientos almacenados es muy potente. Permiten ejecutar
operaciones complejas en pocos pasos ya que poseen un conjunto de instrucciones avanzado.

Por su Centralización: al formar parte de la base de datos los procedimientos almacenados están en un
lugar centralizado y pueden ser ejecutados por cualquier aplicación que tenga acceso a la misma.

Ejemplos.

 Ejemplo de Procedimiento almacenado  para insertar registros.


 Ejemplo de Procedimiento almacenado  para actualizar registro.

 Ejemplo de Procedimiento almacenado mixto (inserción y actualización)


Nota1: Estos mismos procedimientos se utilizaran en el programa a la cual hace
referencia esta asignación VIII

2)Elabora un programa que permita:


Crear,Consultar , Insertar y Actualizar  productos utilizando procedimientos almacenados desde
C#.

Nota2: Profe el código se dividió en dos etapas, cree una clase para la conexión de la
base de datos con C#, el Formulario Principal Load, Acorde fui investigando y tomando
como referencia la clase que usted impartió fui remodelando un poco la programación,
esto como vía de fortalecimiento en el aprendizaje

Código en la Clase para Conexión.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
namespace V_CRUD
{
class DB_Conexion
{
//CREACION DE LA CONEXION CON LA BASE DE DATOS
SqlConnection CONN = new SqlConnection(@"Data source =JP-PC\SQLEXPRESS; initial
Catalog =DB_Ferreteria; Integrated Security = True"); // Cadena de conexion.
public SqlCommand CMD; // DECLARAMOS UN OBJECTO TIPO SQLCOMMAND PARA REALIZAR LAS
CONSULTAS.

public void abrirConexion() //METODO PARA ABRIL LA CONEXION


{
try // CAPTURADOR DE ERRORES
{
CONN.Open();
MessageBox.Show("Conexion establecidad");

}
catch(Exception ex)
{
MessageBox.Show("Error al establecer la conexion" + ex.Message, "Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
CONN.Close();
}

// METODO PARA CARGAR LA BASE DE DATOS AL DATAGRIDVIEW


public DataTable dgvMostral(string Query) // UTILIZANDO LA LIBRERIA SYSTEM.DATA
DECALRAMOS UN OBJECTO TIPO DATATABLE.
{
DataTable DT = new DataTable(); //DECLARAMOS UN DATA TABLE PARA REPRESENTAR
LOS DATOS
SqlCommand CMD = new SqlCommand(); // DECLARAMOS UN SQLCOMMAND PARA PASAR LA
CONSULTA.
SqlDataAdapter DA = new SqlDataAdapter(); //DECLARAMOS UN SQLADAPTER PARA
LLENAR EL DATASET
DataSet DS = new DataSet(); //

DA.SelectCommand = new SqlCommand(Query, CONN);


DA.Fill(DS);
DT = DS.Tables[0];
return DT;
}

//PROCEDIMIENTO PARA INSERAR DATOS A LA BASE DE DATOS


public bool insrtarDatos(string Query)
{
bool insert = false;
CONN.Open();
int i = 0;
CMD = new SqlCommand(Query, CONN);
i = CMD.ExecuteNonQuery();
if(i > 0)
{
return true;
}
CONN.Close();
return insert;
}

//PROCEDIMIENTO PARA EDITAR DATOS A LA BASE DE DATOS


public bool EditarDatos(string Query)
{
bool editar = false;
CONN.Open();
int ED = 0;
CMD = new SqlCommand(Query, CONN);
ED = CMD.ExecuteNonQuery();
if (ED > 0)
{
return true;
}
CONN.Close();
return editar;
}

//PROCEDIMIENTO PARA ELIMINAR DATOS A LA BASE DE DATOS


public bool EliminarDatos(string Query)
{
bool eliminar = false;
CONN.Open();
int E = 0;
CMD = new SqlCommand(Query, CONN);
E = CMD.ExecuteNonQuery();
if (E > 0)
{
return true;
}
CONN.Close();
return eliminar;
}

//METODO PARA BUSCAR DATOS A LA BASE DE DATOS


public bool Buscar(string Query)
{
bool buscar = false;
CONN.Open();
int B = 0;
CMD = new SqlCommand(Query, CONN);
B = CMD.ExecuteNonQuery();
if (B > 0)
{
return true;
}
CONN.Close();
return buscar;
}

}
Código en el Formulario Principal Load.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace V_CRUD
{

public partial class FormAlmacen : Form


{
public FormAlmacen()
{
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e)


{
Close();
}

private void FormAlmacen_Load(object sender, EventArgs e)


{
DB_Conexion CargarDgv = new DB_Conexion(); // TRAEMOS LA CLASE DONDE ESTA LA
CONEXION Y METODOD.
//CARGAMOS LOS DATOS DE LA BASE DE DATOS EN EL DATAGRIDVIEW.
dgvMostral.DataSource = null;
dgvMostral.DataSource = CargarDgv.dgvMostral("SELECT * FROM PRODUCTO");
}

//CREACION DEL METODO ACTUALIZAR DATAGRIDVIEW


public void ACTULIZARGRID()
{
DB_Conexion CargarDgv = new DB_Conexion();
dgvMostral.DataSource = null;
dgvMostral.DataSource = CargarDgv.dgvMostral("SELECT * FROM PRODUCTO");
}
//METODO PARA LIMPIAR LOS CAMPOS, UTLIZANDO EL METODO CLEAR.
public void LIMPIAR()
{
txtCategoria.Clear();
txtNombre.Clear();
txtPrecio.Clear();
txtStock.Clear();
txtMarca.Clear();
txtEstatus.Clear();

private void btnNuevo_Click(object sender, EventArgs e)


{
DB_Conexion DBinsrt = new DB_Conexion(); // LLAMADA DE LA CLASE DONDE ESTA LA
CONEXION Y LOS DIFERENTES METODOS.

try // INICIALIZAMOS UN CAPTURADOR DE ERRORES


{
string INSERTAR; //DECLARAMOS UNA VARIABLE PARA PASAR LA CONSULTA.
INSERTAR = "insert into PRODUCTO VALUES
('"+Convert.ToInt32(txtCategoria.Text)
+"','"+txtNombre.Text+"','"+txtMarca.Text+"','"+Convert.ToInt32(txtPrecio.Text)
+"','"+Convert.ToInt32(txtStock.Text)+"','"+txtEstatus.Text+"')";
if (DBinsrt.insrtarDatos(INSERTAR)) // CONDICIONAL QUE VALIDAD SI SE
INSERTO UN DATOS.
{
MessageBox.Show("Registro Exitoso", "Registrado",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error al insetar datos");
}
LIMPIAR();
ACTULIZARGRID();

}
catch(Exception EX)
{
MessageBox.Show("Error al registral" + EX.Message, "Error:(");
}

private void btnEditar_Click(object sender, EventArgs e)


{
DB_Conexion DBedictar = new DB_Conexion();

try // INICIALIZAMOS UN CAPTURADOR DE ERRORES


{
string EDITAR;
EDITAR = "update PRODUCTO set id_Categoria='" +
Convert.ToInt32(txtCategoria.Text) + "', Nombre='" + txtNombre.Text + "', Marca='" +
txtMarca.Text + "', Precio='" + Convert.ToInt64(txtPrecio.Text) + "', Stock='" +
Convert.ToInt64(txtStock.Text) + "', Estatus='" + txtEstatus.Text + "' where
id_Producto='" + Convert.ToInt32(lbID.Text) + "' ";

if (DBedictar.EditarDatos(EDITAR))
{
MessageBox.Show("Registro actualizado", "Actualizado ☻",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error al insetar datos");
}
LIMPIAR();
ACTULIZARGRID();

}
catch (Exception EX)
{
MessageBox.Show("Error al editar " + EX.Message, "Error :(");
}

private void dgvMostral_CellClick(object sender, DataGridViewCellEventArgs e)


{
if(e.ColumnIndex == 0) //EVENTO CLICKCELL QUE SELECIONA UN CAMPO DEL
DATAGRIDVIEW PARA EDITAR LA CONSULTA.
{
lbID.Text = dgvMostral.CurrentRow.Cells[0].Value.ToString();
txtCategoria.Text = dgvMostral.CurrentRow.Cells[1].Value.ToString();
txtNombre.Text = dgvMostral.CurrentRow.Cells[2].Value.ToString();
txtMarca.Text = dgvMostral.CurrentRow.Cells[3].Value.ToString();
txtPrecio.Text = dgvMostral.CurrentRow.Cells[4].Value.ToString();
txtStock.Text = dgvMostral.CurrentRow.Cells[5].Value.ToString();
txtEstatus.Text = dgvMostral.CurrentRow.Cells[6].Value.ToString();
}
}

private void btnEliminar_Click(object sender, EventArgs e)


{
DB_Conexion DELETE = new DB_Conexion();

try // INICIALIZAMOS UN CAPTURADOR DE ERRORES


{
string eliminarD;
eliminarD = "delete from PRODUCTO where Id_Producto='" +
Convert.ToInt32(lbID.Text) + "'";

if (DELETE.EditarDatos(eliminarD))
{
MessageBox.Show("Registro eliminado", "Eliminado",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error al insetar datos");
}
LIMPIAR();
ACTULIZARGRID();

}
catch (Exception EX)
{
MessageBox.Show("Error al editar " + EX.Message, "Error :(" ,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void txtbuscar_KeyUp(object sender, KeyEventArgs e) // DECLARAMOS UN


EVENTO LLAMDO KEYUP PARA REALIZAR LA BUSQUEDA POR NOMBRE
{
DB_Conexion buscarDB = new DB_Conexion();
//CONSULTA PARA REALIZAR LA BUSQUE MEDIATEDA UN NOMBRE O UN ID
dgvMostral.DataSource = buscarDB.dgvMostral("select * from PRODUCTO where
Nombre like '"+txtbuscar.Text+"%'");
}

private void button1_Click(object sender, EventArgs e)


{
//LLAMADA DEL FORMULARIO VER CATEGORIA
FormVerCategoria categoria = new FormVerCategoria();
categoria.ShowDialog();
categoria.BringToFront();
txtCategoria.Text = Datos.Categoria;
}

private void dgvMostral_CellContentClick(object sender, DataGridViewCellEventArgs


e)
{

}
}
}

Captures

También podría gustarte