从DAO用JDBC传SQL语句给数据库操作批量删除行
比如批量删除 ID 为 3,15,29的行
1.传参为数组 int[] = {3,15,29}
2.将数组内容输入并转换为(3,15,29)——难点,而且想用两行代码解决
3.执行就好多了,拼SQL语句,执行,提交
代码如下,重点是步骤二的摸索
public Integer deleteBatch(int[] array) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
//常干的三件事:驱动连接自动提交
Class.forName( "com.mysql.jdbc.Driver" );
connection = java.sql.DriverManager.getConnection( "jdbc:mysql://localhost:3306/test_db", "root", "123456" );
connection.setAutoCommit( false );
//start 拼SQL语句:
String inWhere = Arrays.toString( array ).replace( "[", "(" ).replace( "]", ")" );
String sql2 = new StringBuilder("delete from users where u_id in ").append(inWhere).toString();
System.out.println( sql2 );//end
int update = connection.prepareStatement( sql2 ).executeUpdate();
connection.commit();
return update;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return -1;
}