项目中使用mysql分库分表查询,表名后面往往要带后缀,比如同一张用户表拆成16张,在数据库中就有16张用户表如:
user_01 user_02 … user_16
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 = ?