JdbcDemo.java文件:
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.List;
//释放资源
//JDBC编码的代码模板
public class JdbcDemo5 {
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15", "root", "");
stmt = conn.createStatement();
rs = stmt.executeQuery("select id,name,password,email,birthday from users");
while(rs.next()){
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getDate("birthday"));
users.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
for(User u : users){
System.out.println("users:"+u);
}
}
}
User.java文件:
import java.util.Date;
public class User {
private int id;
private String name;
private String password;
private String email;
private Date birthday;
public User() {
super();
}
public User(int id, String name, String password, String email,
Date birthday) {
super();
this.id = id;
this.name = name;
this.password = password;
this.email = email;
this.birthday = 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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password
+ ", email=" + email + ", birthday=" + birthday + "]";
}
}
运行结果:
users:User [id=1, name=zs, password=123456, email=zs@sina.com, birthday=1980-12-04]
users:User [id=2, name=lisi, password=123456, email=lisi@sina.com, birthday=1981-12-04]
users:User [id=3, name=wangwu, password=123456, email=wangwu@sina.com, birthday=1979-12-04]