class ConsultasSQL
{
private SqlConnection conexion = new SqlConnection("Data source = JoseM;
Initial catalog = Trabajo_Dise; Integrated security = true ");
private DataSet ds;
public DataTable MostrarDatos()
{
conexion.Open();
SqlCommand cmd = new SqlCommand("select * from tb_cliente",
conexion);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ds = new DataSet();
ad.Fill(ds, "tabla");
conexion.Close();
return ds.Tables["tabla"];
}
public DataTable Buscar(string nombre)
{
conexion.Open();
SqlCommand cmd = new SqlCommand(string.Format("select * from
tb_cliente where nombre like '%(0)%'",nombre), conexion);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ds = new DataSet();
ad.Fill(ds, "tabla");
conexion.Close();
return ds.Tables["tabla"];
}
public bool insertar(string cod_cliente, string nombre, string direccion,
string edad, string telefono)
{
conexion.Open();
SqlCommand cmd = new SqlCommand(string.Format("insert into tb_cliente
values ({0}, '{1}','{2}',{3},'{4}')", new string[] { cod_cliente, nombre,
direccion, edad, telefono }),conexion);
int filasafectadas = cmd.ExecuteNonQuery();
conexion.Close();
if (filasafectadas > 0) return true;
else return false;
}
}
public bool eliminar (string cod_cliente)
{
conexion.Open();
SqlCommand cmd = new SqlCommand(string.Format("Delete from tb_cliente
where cod_cliente = {0}", cod_cliente), conexion);
int filasafectadas = cmd.ExecuteNonQuery();
conexion.Close();
if (filasafectadas > 0) return true;
else return false;
}
public bool Actualizar(string cod_cliente, string nombre, string
direccion, string edad, string telefono)
{
conexion.Open();
SqlCommand cmd = new SqlCommand(string.Format("update tb_cliente set
nombre = '{0}', direccion = '{1}',edad = '{2}',telefono ='{3}' where cod_cliente
= {4}", new string[] { nombre, direccion, edad, telefono, cod_cliente }),
conexion);
int filasafectadas = cmd.ExecuteNonQuery();
conexion.Close();
if (filasafectadas > 0) return true;
else return false;
BOTONES:
Abajo de initializecomponent : ConsultasSQL sql = new ConsultasSQL();
textBox1.Text = dataGridView1.Rows.Count.ToString();
if (sql.insertar(textBox1.Text, textBox2.Text, textBox3.Text,
textBox4.Text, textBox5.Text))
{
MessageBox.Show("Datos insertados");
dataGridView1.DataSource = sql.MostrarDatos();
}
else MessageBox.Show("No se han podido insertar los datos");
}
private void button2_Click(object sender, EventArgs e)
{
if(sql.eliminar(textBox1.Text))
{
MessageBox.Show("Datos eliminados");
dataGridView1.DataSource = sql.MostrarDatos();
}
else MessageBox.Show("No se han podido eliminar los datos");
}
private void button3_Click(object sender, EventArgs e)
{
if(sql.Actualizar(textBox1.Text, textBox2.Text, textBox3.Text,
textBox4.Text, textBox5.Text))
{
MessageBox.Show("Datos Actualizados");
dataGridView1.DataSource = sql.MostrarDatos();
}
else MessageBox.Show("No se han podido actualizar los datos");
}