开发步骤:
1.私有化构造函数,外界无法直接创建对象;
2.提供公共的,静态的,getConnection方法,用来给外界提供数据库连接;
3.提供公共的,静态的,close方法,用来释放资源;
JDBCUtils.java
package cn.yikuan.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; /** * 这个类用来提供JDBC的工具类 * @author Administrator * */ public class JDBCUtils { //1.私有化构造函数,外界无法直接创建对象 private JDBCUtils(){ } static ResourceBundle rb = null; static { //读取属性文件 rb = ResourceBundle.getBundle("jdbc"); } //2.提供公共的,静态的,getConnection方法,用来给外界提供数据库连接 public static Connection getConnection(){ try { //2.1注册驱动 Class.forName(rb.getString("driverClass")); //2.2获取数据库连接 String url = rb.getString("jdbcUrl"); String user = rb.getString("user"); String password = rb.getString("password"); Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (Exception e) { e.printStackTrace(); } return null; } //3.提供公共的,静态的,close方法,用来释放资源 public static void close(ResultSet rs,Statement st,Connection conn){ //3.1非空判断,防止空指针异常 //3.2手动置为空,保证完全释放 if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { rs = null; } } if(st != null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } finally { st = null; } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } finally { conn = null; } } } }
TestUtils.java
package cn.yikuan.test; /** * 这个类用来测试工具类 */ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.Test; import cn.tedu.util.JDBCUtils; public class TestUtils { @Test public void hello(){ Connection conn = null; Statement st = null; ResultSet rs = null; try { //1.注册驱动;//2.获取数据库连接 java.sql.Connection; conn = JDBCUtils.getConnection(); //3.获取传输器 st = conn.createStatement(); //4.执行sql String sql = "select * from user"; rs = st.executeQuery(sql); //5.遍历结果集 while(rs.next()){ String id = rs.getString(1); //String id = rs.getString("id"); String username = rs.getString(2); String password = rs.getString(3); System.out.println(id+username+password); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(rs, st, conn); } } }