简体   繁体   中英

how to handle \ in query mysql

I have a procedure in which I am making query as string then prepare query and execute.

Here is the procedure

CREATE DEFINER=`root`@`%` PROCEDURE `dim_add_customer`(
IN _customer_id BIGINT(20) ,
IN _first_name VARCHAR(50) ,
)
BEGIN
    SET @_query := CONCAT('first_name = "',_first_name,'"');
    SET @_query := CONCAT('UPDATE customer_detail SET ',@_query,' WHERE customer_id = ',_customer_id);
    PREPARE stmt FROM @_query;

END$$
DELIMITER ;

Now when I call

call dim_add_customer(1,'abc\\')

Then there is issue in creating string query.The query it made

UPDATE customer_detail SET first_name = "abc\" WHERE customer_id = 1

is there any best solution to solve this ?

You shouldn't build the queries by concat.

You should use the parameters in the query like

SET @_query="UPDATE customer_detail 
   SET first_name=@_first_name 
   WHERE customer_id = @_customer_id" 

I'm not sure if you can declare your variables directly from the input parameters like

CREATE DEFINER=`root`@`%` PROCEDURE `dim_add_customer`(
IN @_customer_id BIGINT(20) ,
IN @_first_name VARCHAR(50) ,

)

or you have to

SET @_customer_id = _customer_id
SET @_first_name = _first_name

CAVEAT: I'm used to the MsSql-way of creating procedures with variables; I might have misunderstood something, but at least creating sql by concat should be your last resort.

Creating queries by concat is the equivalent of

x=1
q=concat("y=",x,"+2")
eval (q)

instead of

x=1
y=x+2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM