返回的查询数据表的结果是多行的情况:
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class DBUtils_Use {
@Test
public void testQueryMany() throws SQLException {
Connection connection = JDBCUtilsByDruid.getConnection();
QueryRunner queryRunner = new QueryRunner();
String sql = "select id, name from actor where id >= ?";
List<Actor> list =
queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
System.out.println("输出集合的信息");
for(Actor actor : list) {
System.out.print(actor);
}
JDBCUtilsByDruid.close(null, null, connection);
}
}
返回结果是单行记录:
@Test
public void testQuerySingle() throws SQLException {
Connection connection = JDBCUtilsByDruid.getConnection();
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from actor where id = ?";
Actor actor =
queryRunner.query(connection, sql, new BeanHandler<>(Actor.class), 2);
System.out.print(actor);
JDBCUtilsByDruid.close(null, null, connection);
}
返回结果是单行单列:
@Test
public void testScalar() throws SQLException {
Connection connection = JDBCUtilsByDruid.getConnection();
QueryRunner queryRunner = new QueryRunner();
String sql = "select name from actor where id = ?";
Object obj = queryRunner.query(connection, sql, new ScalarHandler(), 2);
System.out.print(obj);
JDBCUtilsByDruid.close(null, null, connection);
}
|