cmd.CommandType = CommandType.Text - Why use?

1

Have a good day.

I am populating a grid, and after searching the internet, I saw that some use the command:

cmd.CommandType = CommandType.Text;

My question is, why use? what's the difference? I did some testing here, and it works normally with or without this parameter.

Follow my code:

 private void Form1_Load(object sender, EventArgs e)
    {
        string sqlstring, _sql;
        int id_cliente = 3;

        sqlstring = @"Server=tcp:tpspoazsql01.database.windows.net,1433;Data Source=tpspoazsql01.database.windows.net;Initial Catalog=Onee;Persist Security Info=False;User ID=********;Password=*********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
        _sql = string.Empty;

        SqlConnection sqlconn = new SqlConnection(sqlstring);

        try
        {
            _sql = @"SELECT nome,endereco,numero,bairro,cidade,estado,cep FROM Cliente_enderecos_alter WHERE id_cliente = @id_cliente AND tipo = 'Cobrança'";
            SqlCommand cmd = new SqlCommand(_sql, sqlconn);
            cmd.Parameters.Add("@id_cliente", SqlDbType.Int).Value = id_cliente;

            sqlconn.Open();

            cmd.CommandType = CommandType.Text;

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable clientes = new DataTable();
            da.Fill(clientes);

            dataGridView1.DataSource = clientes;
        }
        catch
        {

        }
    }
    
asked by anonymous 11.07.2016 / 13:18

2 answers

2

It turns out that the default of the CommandType property is CommandType.Text . So it works even without you explicitly explaining it.

This does not mean that your command will work without this, it will always be necessary to have some value in this property. The possible values are:

  • StoredProcedure - Performs a procedure. The command will be the name + parameters of this procedure;
  • TableDirect - Returns information about a table. The command should be the name of the table;
  • Text - The command must be SQL.
  • See in the screenshot that at the moment the object is created CommandType is already CommandType.Text .

        
    11.07.2016 / 13:29
    2

    You do not need to use this case. In your example, CommandType makes no difference, because the default value of an enum of CommandType is CommandType.Text value.

    CommandType can be modified when you want to call a Procedure % using the Parameters % of SqlCommand in order to guarantee some validations as SQL Injection . ( CommandType.StoredProcedure for this)

    It also has another option of TableDirect , but I've never used it and I do not know it right, so I'm just commenting on it in case I want to search.

    Here the OS have a question that shows how to use StoredProcedure with Parameters .

        
    11.07.2016 / 13:29