jdbc工具类抽取分为两部分
1.创建连接
2.关闭所有链接。
案例如下:
public class DBUtils {
private static String driverClass;
private static String url;
private static String username;
private static String password;
static{
ResourceBundle rb=ResourceBundle.getBundle("dbinfo");
driverClass=rb.getString("driverClass");
url=rb.getString("url");
username=rb.getString("username");
password=rb.getString("password");
System.out.println(driverClass+"======="+url+"=============="+username+"-------------"+password);
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//创建连接
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,username,password);
}
//关闭资源
public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
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;
}
}
}
3.dbinfo.properties文件(注意文件中不包含分号)
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/shop
username=root
password=123
4.junit测试:
public class TestCurd {
@Test
public void testSelect(){
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
conn=DBUtils.getConnection();
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from users");
List<User> list=new ArrayList<User>();
while(rs.next()){
User u=new User();
u.setId(rs.getInt(1));
u.setName(rs.getString(2));
u.setPassword(rs.getString(3));
u.setBirthday(rs.getString(5));
u.setEmail(rs.getString(4));
list.add(u);
}
for(User user:list){
System.out.println(user);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtils.closeAll(rs, stmt, conn);
}
}
}
4.1 插入操作:
案例 代码如下:
public void testInsert() {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DBUtils.getConnection();
stmt=conn.prepareStatement("insert into users(id,username,password,email,birthday)values(?,?,?,?,?)");
stmt.setInt(1, 20);
stmt.setString(2, "zxg");
stmt.setString(3, "123");
stmt.setString(4, "1009@qq.com");
stmt.setString(5, "1993-05-25");
int i=stmt.executeUpdate();
if(i>0){
System.out.println("success");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtils.closeAll(null, stmt, conn);
}
}
简单的CRUD操作,可以只替换或修改测试部分的代码和sql语句即可;