package cn.itcast.jdbc; import cn.itcast.domain.User; import java.sql.*;import java.util.ArrayList;import java.util.List; /** * @author newcityman * @date 2019/8/13 - 23:27 */public class JDBCDemo06 { public static void main(String[] args) { JDBCDemo06 demo06 = new JDBCDemo06(); demo06.findAll(); } public List<User> findAll() { Connection conn = null; Statement stmt = null; ResultSet rs = null; List<User> list = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day13", "root", "123"); stmt = conn.createStatement(); String sql = "select * from user"; rs = stmt.executeQuery(sql); list = new ArrayList<User>(); User user = null; //遍历集合 while (rs.next()) { int id = rs.getInt("id"); String username = rs.getString("username"); String password = rs.getString("password"); String sex = rs.getString("sex"); Date birthday = rs.getDate("birthday"); String hobbys = rs.getString("hobbys"); String des = rs.getString("des"); //封装对象 user = new User(); user.setId(id); user.setUsername(username); user.setPassword(password); user.setSex(sex); user.setBirthday(birthday); user.setHobbys(hobbys); user.setDes(des); //装载集合 list.add(user); } System.out.println(list); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; }}
原文地址:https://www.cnblogs.com/newcityboy/p/11349394.html
时间: 2024-10-08 05:18:12