初学JDBC,JDBC工具类的简单封装

//工具类不需要被继承

public final class JdbcUtils{

  //封装数据库连接参数,便于后期更改参数值

  private static String url="jdbc:mysql://localhost:3306/jdbc";

  private static String user="userName";

  private static String password="password";

  //无需被创建对象

  private JdbcUtils(){}

  //静态代码块:在项目启动时候执行

  static{

    try{

      Class.forName("com.mysql.jdbc.Driver");

      }catch(ClassNotFoundException e){

       throw new IninitializerError(e);

      }

    }

  //创建数据库连接

  public static Connection getConnetcion() throws SQLException{

  return DrivaerManager.getConnetcion(url,user,password);

  }

  //释放资源

  public static void freeResource(ResultSet resultSet,Statement statement,Connection conn){

  try{

    if(resultSet!=null)

      resultSet.close();

  }catch(SQLException e){

    e.printStackTrace();

  }finally{

   try{

    if(statement!=null)

      statement.close();

    }catch(SQLException e){

    e.printStackTrace();

    }finally{

     try{

       if(conn!=null)

        conn.close();

      }catch(SQLException e){

        e.printStackTrace();

      }

  }

  }

}

}

//示例

public class UserDao{

  public static void testGetUsers() throws Exception{

    Connection conn=null;

    Statement statement=null;

    ResultSet resultSet=null;

    try{

      conn=JdbcUtils.getConnetcion();

      statement=conn.createStatement();

      resultSet=statement.excuteQuery("select * from user");

      while(resultSet.next()){

        System.out.println(resultSet.getObject(1)+"\t"+resultSet.getObject(2));

      }

    }finally{

      JdbcUtils.freeResource(resultSet,statement,conn);

    }

  }

}

 

你可能感兴趣的:(jdbc)