DBUtils使用
package jdbc;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class DbUtilsTest {
@Test
public void update() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
Connection connection = Druid.getConnection();
String sql = "insert into t_user(username,password,email) values(?,?,?)";
int update = queryRunner.update(connection,sql, "小花", 123456, "xiaohua@qq.com");
System.out.println("影响了"+update+"条记录");
}
@Test
public void queryOne() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
Connection connection = Druid.getConnection();
String sql = "SELECT `id`,`username`,`password`,`email` FROM t_user WHERE id = ?";
BeanHandler<User> handler = new BeanHandler<User>(User.class);
User user = queryRunner.query(connection, sql, handler, 1);
System.out.println(user);
DbUtils.close(connection);
}
@Test
public void queryMore() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
Connection connection = Druid.getConnection();
String sql = "SELECT `id`,`username`,`password`,`email` FROM t_user WHERE id > ?";
BeanListHandler<User> handler = new BeanListHandler<User>(User.class);
List<User> userList = queryRunner.query(connection, sql, handler, 1);
userList.forEach(System.out::println);
DbUtils.close(connection);
}
@Test
public void queryScalar() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
Connection connection = Druid.getConnection();
String sql = "SELECT count(*) FROM t_user WHERE id > ?";
ScalarHandler handler = new ScalarHandler();
long count = (long) queryRunner.query(connection, sql, handler, 1);
System.out.println(count);
DbUtils.close(connection);
}
@Test
public void result() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
Connection connection = Druid.getConnection();
String sql = "SELECT `id`,`username`,`password`,`email` FROM t_user WHERE id = ?";
ResultSetHandler<User> handler = new ResultSetHandler<User>(){
@Override
public User handle(ResultSet resultSet) throws SQLException {
if (resultSet.next()){
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
String password = resultSet.getString("password");
String email = resultSet.getString("email");
return new User(id, username, password, email);
}
return null;
}
};
User user = queryRunner.query(connection, sql, handler, 1);
System.out.println(user);
DbUtils.close(connection);
}
}