The difference between # and $ in sql

First, use # {} here, when using #:

1. Used to pass in parameters, sql will add "" when parsing, as a string to parse, such as role_id = "roleid";

2. # {} can largely prevent SQL injection;

extend:

1. Use {roleId, jdbcType = INTEGER}, then the value of sql when analyzing is roleId = roleId, and an error will be reported during execution;

2. The $ {} method cannot prevent SQL injection;

3. $ is generally used for incoming database objects, such as database table names;

4. Try to use # {} when you can use # {};

note:

Note that when using order by dynamic parameters when sorting mybaties, use $ {} instead of # {};

 

Second, the main difference is # with double quotes, $ without

For example: # {id} stands for 'id', $ {id} stands for id

 

The following is the sql of Mybatis @Select annotation

@Select("select id,name from user where id=#{id}")
public User getUser(@Param("id")long id);

@Select("select id,name from user where id=${id}")
public User getUSer(@Param("id")long id);

If the id passed in is 1, the actual sql is

select id,name from user where id='1'

select id,name from user where id=1

There is a case of Mybaits method

@Select("select id,name from user where id=#{id}")
public User getUser(@Param("id") long id);

@Select("select id,name from user where id=#{id}")
public User getUser(long id);

The second is because you can omit @Param ("") because you pass a parameter, but you cannot use $ {} in this case.

When passing more than two parameters, you must write @Param ("")

 

Guess you like

Origin www.cnblogs.com/xxl910/p/12713904.html