数据库工具类第一版(DBUtils)
只是将一些重复的代码封装到一个类中去:
代码:
实体类User
package test_path.entity;
public class User {
//专门用来映射mysql数据库的t_user映射的。建议其中的属性名或成员变量和表中的字段名保持一致
private Integer id;
private String uname;
private String upwd;
private String birth;
public User() {
}
public User(Integer id, String uname, String upwd, String birth) {
this.id = id;
this.uname = uname;
this.upwd = upwd;
this.birth = birth;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", uname='" + uname + '\'' +
", upwd='" + upwd + '\'' +
", birth='" + birth + '\'' +
'}';
}
}
工具类
package test_path;
import test_path.entity.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TestUtilsOne {
public static void main(String[] args) {
Connection connection=JDBCUtilsOne.getConnection();
String sql="select * from t_user";
PreparedStatement ps = null;
ResultSet rs = null;
List<User> list= null;
try {
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
list = new ArrayList<>();
while(rs.next()){
User user=new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
for(User u:list){
System.out.println(u);
}
JDBCUtilsOne.close(connection,ps,rs);
}
}
测试工具类代码:
package test_path;
import test_path.entity.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TestUtilsOne {
public static void main(String[] args) {
Connection connection=JDBCUtilsOne.getConnection();
String sql="select * from t_user";
PreparedStatement ps = null;
ResultSet rs = null;
List<User> list= null;
try {
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
list = new ArrayList<>();
while(rs.next()){
User user=new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
for(User u:list){
System.out.println(u);
}
JDBCUtilsOne.close(connection,ps,rs);
}
}