zoukankan      html  css  js  c++  java
  • 初学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)+" "+resultSet.getObject(2));

          }

        }finally{

          JdbcUtils.freeResource(resultSet,statement,conn);

        }

      }

    }

  • 相关阅读:
    【leetcode】Validate Binary Search Tree
    【leetcode】Add Binary
    【leetcode】Search a 2D Matrix
    绑定方法与非绑定方法||反射||内置方法
    封装||property
    组合||抽象类||多态||鸭子类型
    在子类中重用父类的属性
    继承||派生||继承实现原理
    面向对象小练习
    面向对象编程
  • 原文地址:https://www.cnblogs.com/hujiapeng/p/4638144.html
Copyright © 2011-2022 走看看