REALIZAR CONSULTAS CON C# a una Base de Datos de SQL

Agregar la librerías de SQL:

usingSystem.Data.Sql;
usingSystem.Data.SqlClient;


Agregar las 2 líneas SqlConnection y SqlCommand:


  public partial class MainWindow : Window
    {
        SqlConnectionconexion = new SqlConnection(); //<-- data-blogger-escaped-span="">
        SqlCommandcomando = new SqlCommand();        //<-- data-blogger-escaped-span="">
        public MainWindow()
        {
            InitializeComponent();




Código del botón:

privatevoid btnBuscar(objectsender, RoutedEventArgs e)
        {
            conexion.ConnectionString = @"Data Source=LCCSYHB_32;Initial Catalog=CSharp_Ejercicios;Integrated Security=True";

            comando.Connection = conexion;
            conexion.Open();
            stringquery = "SELECT * FROM CLIENTES WHERE Cliente = @Cliente";
            SqlCommandcmd = new SqlCommand(query, conexion);
            cmd.Parameters.AddWithValue("@Cliente", Convert.ToInt32(TxtCliente.Text));
            SqlDataReaderdr = cmd.ExecuteReader();
            if(dr.Read())
            {
                LblNombre.Content = dr["Nombre"].ToString() + " " + dr["Apellidos"].ToString();
                LblDireccion.Content = dr["Direccion"].ToString();
             }
            conexion.Close();
           
        }






0 comentarios: