C# how to do database search using parameters

Asked

Viewed 514 times

4

I have the following code

public DataTable PesquisarPorNome(string NomePesquisado)
{
    try
    {
        DataTable tabela = new DataTable();
        SqlDataAdapter adaptador = new SqlDataAdapter("SELECT * FROM tbEspecialidades WHERE NomeEspecialidade LIKE '%" + NomePesquisado + "%' ", conexao.StringConexao);
        adaptador.Fill(tabela);
        return tabela;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    finally
    {
        conexao.DesconectarDoBanco();
    }
}

I know that if I make this available, the cow goes to the swamp, because SQL Injection is there for this, but how to use parameters ? Thank you

  • Which database you’re using?

  • Sorry, I’m not receiving notifications, I’m using SQL

  • Antonio, the Structured Query Language (SQL) is a language to query databases.

  • 1

    Ok, I don’t know if I understand your question, I’m using MSSQL . I know that SQL is a language , that we often confuse with MSSQL is that SGBD.

2 answers

4


See the example below,

public DataTable PesquisarPorNome(string NomePesquisado)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = myConnString;
        try
        {
            var SQL = string.Format("SELECT * FROM tbEspecialidades WHERE NomeEspecialidade  LIKE @NomePesquisado");

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = SQL;
            cmd.Parameters.Add("@NomePesquisado", SqlDbType.NVarChar).Value = "%" + NomePesquisado + "%";
            SqlDataAdapter sqlA = new SqlDataAdapter();
            DataTable tabela = new DataTable();

            sqlA.SelectCommand = cmd;

            conn.Open();
            sqlA.Fill(tabela);

            return tabela;
        }
        finally
        {
            conn.Close();
        }
    }

Only you need to specify the database you are using..

3

As soon as you consult with Parameters and LIKE clause.

var cmd = new SqlCommand("SELECT * FROM tbEspecialidades WHERE NomeEspecialidade LIKE '%'+ @NomePesquisado +'%'", connection);
cmd.Parameters.Add("@NomePesquisado", SqlDbType.VarChar, 50).Value = NomePesquisado;
var dr = cmd.ExecuteReader();
  • Who gave downgrade can justify?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.