How to use the LIKE operator [closed]

1

I have this sentence in c # to perform a parameterized or filtered search using the like.

    else if(rbnombre.Checked==true)
        {
            try
            {
                if (txtbusqueda.Text == "")
                {
                    MessageBox.Show("Debe de llenar el campo de filtro para realizar la busqueda", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtbusqueda.Focus();
                }
                else
                {

                    con.Open();
                    SqlCommand consulta = new SqlCommand("SELECT * FROM Usuarios NOMBRE LIKE '%" + txtbusqueda.Text + "%'", con);
                    SqlDataAdapter da = new SqlDataAdapter(consulta);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    dtgv.DataSource = dt;


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("La consulta no arrojo resultados" + ex, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                con.Close();
            }
  

I get this error: incorrect syntax near of keyword 'like'

    
asked by Samuel Ignacio Susana Confesor 05.09.2017 в 20:47
source

3 answers

4

In addition to missing the WHERE clause, it is recommended that you change that way of making queries, since it is prone to attacks by SQL injection .

What I recommend is that you make the query like this, also making use of blocks using :

using(SqlConnection con = new SqlConnection(...))
{
    string Comando = "SELECT * FROM Usuarios WHERE Nombre LIKE @query";
    using (SqlCommand cmnd = new SqlCommand(Comando, con)
    {
        cmnd.CommandType = CommandType.Text;
        cmnd.Parameters.Add(new SqlParameter() {
                                ParameterName = "@query",
                                SqlDbType = SqlDbType.NVarChar,
                                Value = string.Format("%{0}%", txtbusqueda.Text)
                            });

        con.Open();
        using (SqlDataReader dataReader = cmnd.ExecuteReader())
        {
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(consulta);
            dataReader.Dispose();
            da.Fill(dt);
            dtgv.DataSource = dt;
        }
    }
}
    
answered by 05.09.2017 / 21:05
source
2

You have an error in the SQL statement:

 SqlCommand consulta = new SqlCommand("SELECT * FROM Usuarios WHERE NOMBRE LIKE '%" + txtbusqueda.Text + "%'", con);
    
answered by 05.09.2017 в 20:50
1

I need you to add the clause WHERE:

SqlCommand consulta = new SqlCommand("SELECT * FROM Usuarios WHERE NOMBRE LIKE '%" + txtbusqueda.Text + "%'", con);

By the way, your code is very prone to sql injections. I advise you to do a parametrized query .

    
answered by 05.09.2017 в 20:49