当前位置:网站首页>queryRunner. Query method

queryRunner. Query method

2022-07-05 15:16:00 Add gold development

public Map<String, Object> getUserByUserId_MAP(int userId){
Map<String, Object> map = null;
// Get the connection
Connection conn = DBConnectionUtil.getConnection();
// establish SQL Execution tools  
QueryRunner queryRunner = new QueryRunner();
// Splicing SQL
String sql = "select * from user where userId = ?";
Object params[] = {userId};

try {
map = queryRunner.query(conn, sql, new MapHandler(), params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnectionUtil.closeConnection(conn);
}
return map;
}



apache.commons.dbutils.QueryRunner.query Methodical handler Parameters

For the first time to use apache.commons.dbutils.QueryRunner People who visit the database will have a question ..

String url = "jdbc:mysql://localhost:3306/test";
Connection con = DriverManager.getConnection(url, "root", "pwd");
String sql = "select * from myTable";
QueryRunner qr = new QueryRunner();
qr.query(con, sql, handler); //con It's a database connection , sql Is a query statement , handler What is it? ?

QueryRunner.query The return value of the method is a Object object , The Object Object holds the data obtained from the database ,

It is the type of ( Types that can be explicitly converted ) Is called by query Methods handler Parameters determine .


ResultSetHandler handler = new ArrayHandler();
Object obj = qr.query(con, sql, handler);
Object[] arr = (Object[])obj;

ResultSetHandler handler = new ArrayListHandler();
Object obj = qr.query(con, sql, handler);
List list = (List)obj;

in other words , Save data Object The explicit conversion type of the object is handler Parameters determine .

 

Here is handler Comparison table of parameters and return object types :

AbstractListHandler -- Back to multiple lines List The abstract class of

ArrayHandler --  Return a line of Object[]

ArrayListHandler -- return List, Each line is Object[]

BeanHandler -- Return to the first Bean object

BeanListHandler -- return List, Each line is Bean

ColumnListHandler -- Returns a list of List

KeyedHandler -- return Map, See code for details

MapHandler -- Returns a single Map

MapListHandler -- return List, Each line is Map

ScalarHandler -- Returns the first value of the column

原网站

版权声明
本文为[Add gold development]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140516364181.html