【MedusaSTears】DAO批量删除表数据传参思路Delete from table where column in()

版权声明:尊重原作者劳动,转载请标明出处 https://blog.csdn.net/MedusaSTears/article/details/81634191

从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;
	}

猜你喜欢

转载自blog.csdn.net/MedusaSTears/article/details/81634191