package songyan.jdbc.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import songyan.jdbc.entity.User; import com.mysql.jdbc.Driver; public class Demo1 { static Connection conn; static Statement sta; static ResultSet rs; static ArrayList<User> al=new ArrayList<User>(); public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day06", "root", "247418"); sta = conn.createStatement(); rs = sta.executeQuery("select * from users"); while(rs.next()) { User u=new User(); u.setId(rs.getInt("id")); u.setName(rs.getString("name")); u.setPassword(rs.getString("password")); u.setEmail(rs.getString("email")); u.setBirthday(rs.getDate("birthday")); al.add(u); } for(int i=0;i<al.size();i++) { System.out.println(al.get(i).getId()); System.out.println(al.get(i).getName()); System.out.println(al.get(i).getPassword()); System.out.println(al.get(i).getEmail()); System.out.println(al.get(i).getBirthday()); } } catch (Exception e) { e.printStackTrace(); } finally { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs=null; } if(sta!=null) { try { sta.close(); } catch (SQLException e) { e.printStackTrace(); } sta=null; } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn=null; } } } }
package songyan.jdbc.entity; import java.util.Date; public class User { private int id; private String name; private String password; private String email; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }