今天学习jdbc时,终于知道lambda是干啥的了。代码封闭的核心思想原来是这样。
queryOne:
public Account queryOne(int id) {
exeSQL("select * from account where id="+id , new Function() {
@Override
public void execute(PreparedStatement preparedStatement) throws Exception{
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setWealth(resultSet.getDouble("wealth"));
account.setPassword(resultSet.getString("password"));
}
}
});
用于查询一行数据,并将数据封装给account类实例;
匿名类实现接口;因为只提供了函数作用,所以叫函数式接口。函数,不也叫方法么不是?
public void exeSQL(String sql, Function function) {
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Connection connection = DriverManager.getConnection(url);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
function.execute(preparedStatement);
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
exeSQL:执行一个sql语句,并对结果集进行操作function接口
public Account queryOne(int id) {
exeSQL("select * from account where id="+id , preparedStatement -> {
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setWealth(resultSet.getDouble("wealth"));
account.setPassword(resultSet.getString("password"));
}
});
return account;
}
lambda写法
原创,转载随意,没工作好辛苦。