mysql 分库分表中 使用 mybatis 占位符 #和$的区别

项目中使用mysql分库分表查询,表名后面往往要带后缀,比如同一张用户表拆成16张,在数据库中就有16张用户表如:

user_01 user_02  …  user_16

在java实际项目中,我们一般使用sql框架,比如mybatis中#和$在jdbc预编译处理中是不一样的,在jdbc中,数据库操作主要用 PreparedStatement和Statement两个对象。PreparedStatement执行语句会预编译在数据库系统中。执行计划同样会被缓存起来,它允许数据库做参数化查询。使用预处理语句比普通的查询更快,数据库对SQL语句的分析,编译,优化已经在第一次查询前完成了。参数化查询用法如下
1.	public static void main(String args[]) throws SQLException {
2.	        Connection conn = DriverManager.getConnection("mysql:\\localhost:1520", "root", "root");
3.	        PreparedStatement preStatement = conn.prepareStatement("select distinct loan_type from loan where bank=?");
4.	        preStatement.setString(1, "Citibank");	 
6.	        ResultSet result = preStatement.executeQuery();	 
8.	        while(result.next()){
9.	            System.out.println("Loan Type: " + result.getString("loan_type"));
10.	        }       
11.     }

使用占位符?将参数传给已经预编译好的sql语句,这样可以防止sql注入,但传入的参数不能是表名,因为预编译必须得到真实的表名。所以在mybatis mapper文件中,我们要这样写

1.	select * from user_${tableIndex} where id = #{id}

这里使用$生成的sql语句为

select * from user_01 where id = ?


猜你喜欢

转载自blog.csdn.net/calvin4cn/article/details/80142131