0% found this document useful (0 votes)
16 views4 pages

15 - SqlCommand (Delete) Borrar Registro

rrrr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

15 - SqlCommand (Delete) Borrar Registro

rrrr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

15 - SqlCommand (delete) Borrar registro

Otra de las actividades comunes con los datos es la eliminación. Para


eliminar registros de una tabla debemos emplear el comando SQL delete.

Problema

Implementar una aplicación que permita consultar un artículo por su


código. Luego de mostrarlo activar un botón para poder eliminarlo.
Crear un proyecto llamado: PruebaBaseDatos5 y definir la siguiente
interfaz visual:
5 objeto de la clase Label.
2 objeto de la clase Button (disponer la propiedad Enabled del
botón de borrado en false para que empiece desactivo)
1 objeto de la clase TextBox.

El código fuente para resolver la consulta y borrado es:


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;

using System.Data.SqlClient;

namespace PruebaBaseDatos5
{
public partial class Form1 : Form
{
private SqlConnection conexion = new SqlConnection("server=DIEGO-PC ; database=base1 ;
integrated security = true");

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
conexion.Open();
string cod = textBox1.Text;
string cadena = "select descripcion, precio from articulos where codigo=" + cod;
SqlCommand comando = new SqlCommand(cadena, conexion);
SqlDataReader registro = comando.ExecuteReader();
if (registro.Read())
{
label4.Text = registro["descripcion"].ToString();
label5.Text = registro["precio"].ToString();
button2.Enabled = true;
}
else
MessageBox.Show("No existe un artículo con el código ingresado");
conexion.Close();
}

private void button2_Click(object sender, EventArgs e)


{
conexion.Open();
string cod = textBox1.Text;
string cadena = "delete from articulos where codigo=" + cod;
SqlCommand comando = new SqlCommand(cadena, conexion);
int cant;
cant = comando.ExecuteNonQuery();
if (cant==1)
{
label4.Text = "";
label5.Text = "";
MessageBox.Show("Se borró el artículo");
}
else
MessageBox.Show("No existe un artículo con el código ingresado");
conexion.Close();
button2.Enabled = false;
}
}
}
Primero indicamos el espacio de nombres relacionado a la comunicación
con SQL Server:
using System.Data.SqlClient;
Como en los dos métodos utilizamos el objeto SqlConnection lo definimos
como un atributo de la clase Form1:
public partial class Form1 : Form
{
private SqlConnection conexion = new SqlConnection("server=DIEGO-PC ;
database=base1 ; integrated security = true");
El algoritmo de consulta es idéntico al concepto que vimos anteriormente
(solo modificamos la propiedad Enabled del button2):
private void button1_Click(object sender, EventArgs e)
{
conexion.Open();
string cod = textBox1.Text;
string cadena = "select descripcion, precio from articulos where codigo=" + cod;
SqlCommand comando = new SqlCommand(cadena, conexion);
SqlDataReader registro = comando.ExecuteReader();
if (registro.Read())
{
label4.Text = registro["descripcion"].ToString();
label5.Text = registro["precio"].ToString();
button2.Enabled = true;
}
else
MessageBox.Show("No existe un artículo con el código ingresado");
conexion.Close();
}
Lo nuevo aparece en el borrado del artículo que acabamos de consultar,
primer confeccionamos un string con el comando delete:
string cod = textBox1.Text;
string cadena = "delete from articulos where codigo=" + cod;
Luego procedemos a crear un objeto de la clase SqlCommand pasando el
comando SQL de borrado con la referencia de la conexión:
SqlCommand comando = new SqlCommand(cadena, conexion);
Llamamos seguidamente al método ExecuteNonQuery que se comunica
con el SQL Server para que ejecute el comando configurado previamente
y retorna la cantidad de registros afectados (en este caso retorna la
cantidad de registros borrados):
int cant;
cant = comando.ExecuteNonQuery();
Si retorna un uno significa que se borró el artículo con el código
ingresado:
if (cant==1)
{
label4.Text = "";
label5.Text = "";
MessageBox.Show("Se borró el artículo");
}
En pantalla tenemos la siguiente interfaz luego de borrar un artículo
existente:

You might also like