JDBC的实现及注意事项

    定义:JDBC(Java DataBase Connectivity):Java数据库连接。

   工欲善其事必先利其器:

         连接oracle数据库所需的包:https://pan.baidu.com/s/1HMUJYI2osnskp2aO-6qgbg

         连接mysql数据库所需的包:https://pan.baidu.com/s/1ZVjOHeSfMs6KevQF7h4qKg

  从实现功能即可的代码开始

public class MyJdbc{
   public static void main(String[] args) throws Exception{
       //(1)加载驱动
            //连接oracle oracle.jdbc.driver.OracleDriver
            //连接mysql  com.jdbc.mysql.dirver
       Class.forName("oracle.jdbc.driver.OracleDriver");
       //(2)建立数据库连接对象Connenction
       Connection conn = DriverManager.getConnection(
                               "jdbc:oracle:thin:@127.0.0.1:1521:XE",
                                "liu",
                                "root");
       //(3)创建Statement
       String sql = "select * from emp";
       PreparedStatement ps = conn.prepareStatement(sql);
       //(4)通过statement的方法查询sql发往数据库,查询结果封装到resultset返回
       ResultSet rs = ps.executeQuery();
       while(rs.next()){
            int empno = rs.getInt("empno");
            String ename = rs.getString("ename");
            String job = rs.getString("job");
            Date hiredate = rs.getTimestamp("hiredate");
            System.out.println(empno+"==>"+ename+"==>"+job+"==>"+hiredate);
       }
       //(5)关闭资源
       rs.close();
       ps.close();
       conn.close();
   }
}

  注意:

   (1)mian函数里的异常未进行捕获,只是声名,如果出现异常则会直接中断程序,导致(5)可能不执行,资源得不到释放。

   (2)在(3)中可以用PerpareStatement对象也可以使用Statement对象,推荐使用PerpareStatement对象,优点在于:

            1.PerpareStatement类有预处理,效率高。

            2.PerpareStatement类可以防止SQL注入。

   (3)对(2)中DriverManager.getConnection(c1,c2,c3)中三个参数解释:

            c1:jdbc:(oracle:thin/mysql):@ip:端口:数据库类型;

            c2:数据库用户名;

            c3:数据库密码。

    (4)在(4)中语句 Date hiredate = rs.getTimestamp("hiredate")的Date hiredate 属于java.util包,而 rs.getTimestamp("hiredate")得到的Date数据属于java.sql包且是java.util包Date类的子类。

强化版JDBC连接代码

      创建如图所示的项目结构:

JDBC的实现及注意事项_第1张图片

实体类代码:

public class Emp {
    int empno;
    String ename;
    String job;
    Date hiredate;
    double sal;
    int deptno;

    public int getEmpno() {
        return empno;
    }

    public void setEmpno(int empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }
}

    工具类代码:

public class DBLink {
    public static Connection getconn(){
        Connection conn = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection(
                    "jdbc:oracle:thin:@127.0.0.1:1521:XE",
                    "liu",
                    "root");
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeconn(ResultSet r, PreparedStatement ps, Connection conn){
        if(r != null){
            try {
                r.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeconn(PreparedStatement ps, Connection conn){
        closeconn(null,ps,conn);
    }

    public static void main(String[] args) {
        try {
            System.out.println(getconn());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试类代码:

public class EmpDao {
    //根据姓名查找雇员信息
    public static ArrayList sel(Emp e){
        Connection conn = DBLink.getconn();
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList arr = new ArrayList<>();
        String sql = "select * from emp where ename = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,e.getEname());
            rs = ps.executeQuery();
            while (rs.next()){
                Emp emp = new Emp();
                int empno = rs.getInt("empno");
                String ename = rs.getString("ename");
                String job = rs.getString("job");
                Date hiredate = rs.getTimestamp("hiredate");
                double sal = rs.getDouble("sal");
                int deptno = rs.getInt("deptno");
                emp.setEmpno(empno);
                emp.setEname(ename);
                emp.setJob(job);
                emp.setHiredate(hiredate);
                emp.setSal(sal);
                emp.setDeptno(deptno);
                arr.add(emp);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }finally {
            DBLink.closeconn(rs,ps,conn);
            return arr;
        }
    }
    //插入一条信息
    public static void in(Emp e){
        Connection conn = DBLink.getconn();
        PreparedStatement ps =null;
        String sql = "insert into emp(empno,ename,job,hiredate,sal,deptno) values(?,?,?,?,?,?) ";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1,e.getEmpno());
            ps.setString(2,e.getEname());
            ps.setString(3,e.getJob());

            long t =e.getHiredate().getTime();
            Timestamp timestamp = new Timestamp(t);

            ps.setObject(4,timestamp);
            ps.setDouble(5,e.getSal());
            ps.setInt(6,e.getDeptno());
            ps.executeUpdate();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }finally {
            DBLink.closeconn(ps,conn);
        }
    }

    public static void main(String[] args) {
       /*查找
        Emp e = new Emp();
       e.setEname("JONES");
       ArrayList arr =  sel(e);
       for (Emp emp : arr) {
           System.out.println(emp.getEmpno()+"\t"+emp.getEname()+"\t"+emp.getJob()+"\t"+emp.getHiredate()
                    +"\t"+emp.getSal()+"\t"+emp.getDeptno());
        }
        */
        //插入
        Date date = new Date();
        Emp e = new Emp();
        e.setEmpno(9527);
        e.setEname("周星星");
        e.setJob("CLERK");
        e.setHiredate(date);
        e.setSal(1520);
        e.setDeptno(20);
        in(e);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(JDBC的实现及注意事项)