Java Code: Retrieve All Records from 'admin' Table
This is a Java method that retrieves all the records from the 'admin' table in a database and returns them as a list of Admin objects. The SQL query used selects all columns from the table and orders the results by the 'name' column. The method first establishes a database connection using the DBUtil class, creates a prepared statement for the SQL query, executes the query, and iterates through the result set to create Admin objects and add them to the list. Finally, the method closes the result set, statement, and connection before returning the list.
String sql = 'select * from admin order by name';
Connection conn = DBUtil.getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
List<Admin> list = new ArrayList<Admin>();
try {
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
Admin a = new Admin();
a.setId(rs.getInt('id'));
a.setName(rs.getString('name'));
a.setPassword(rs.getString('password'));
a.setAge(rs.getInt('age'));
a.setSex(rs.getString('sex'));
a.setTel(rs.getString('tel'));
a.setPhone(rs.getString('phone'));
a.setAddr(rs.getString('addr'));
a.setMemo(rs.getString('memo'));
list.add(a);
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
DBUtil.close(rs);
DBUtil.close(stmt);
DBUtil.close(conn);
}
return list;
}
原文地址: https://www.cveoy.top/t/topic/n5kQ 著作权归作者所有。请勿转载和采集!