How to quote a variable for Mysql query

Asked

Viewed 1,428 times

3

I’m doing a trial, I need to put a variable varchar in the query, but it doesn’t go with the simple quotes, I tried to concatenate like this or something but it’s no use:

set @comando := concat(@comando, '"'); //ao contrário tbm
set @comando := concat(@comando, classe);
set @comando := concat(@comando, '"');

I’ve had to put triple quotes too:

set @comando := concat(@comando, '''classe''');

What better way to concatenate or make Mysql recognize as a varchar?

Code:

delimiter $$
create procedure eixos_caminhao (in classe varchar(3))
begin
    set @comando := 'select count(*) as qtdeCaminhoes';
    set @comando:= concat(@comando, ' from tb_vbv where classe = ');
    set @comando := concat(@comando, classe);

    PREPARE myquery FROM @comando;
    EXECUTE myquery;
end $$
delimiter;
  • You can do it like this: concat(@comando, ' from tb_vbv where classe = \'');

  • The bar will work as an escape and will make the next character part of the string.

  • then I have to surround with '' on both sides?

  • I’ll add an answer.

  • Beauty! I thank you

1 answer

5


Whenever we’re riding a string and within that string it is necessary to have another string, we have some exits:

  1. As in the SQL so much ' as " begin and end a string, we can interlink these characters to form a string inside the other:

    set @comando = 'select count(*) as qtdeCaminhoes';
    set @comando = concat(@comando, ' from tb_vbv where classe = "');
    set @comando = concat(@comando, classe);
    set @comando = concat(@comando, '"');
    

    The result of this would be:

    select Count(*) as qtyCaminhoes from tb_vbv Where class = "content_de_class"

  2. But if you really want to get around the string with ', you can use the previous reversed method("'"), or use the \ which is an escape character, the ' or " after it, will not be considered as closing a string:

    set @comando = 'select count(*) as qtdeCaminhoes';
    set @comando = concat(@comando, ' from tb_vbv where classe = \'');
    set @comando = concat(@comando, classe);
    set @comando = concat(@comando, '\'');
    

Further information about the function CONCAT is that it accepts several parameters to concatenate at once, its code could be summarized for this for example:

set @comando = 'select count(*) as qtdeCaminhoes';
set @comando = concat(@comando, ' from tb_vbv where classe = ');
set @comando = concat(@comando, '\'', classe, '\'');
  • Got it! is working now my query. Thanks! helped me a lot!

Browser other questions tagged

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