文章目录
 
 
1.什么是JDBC?
 
- JDBC全称Java Database Connectivity 是基于Java语言访问数据库的一种技术,一种用于执行SQL语言的Java API,可以为多种关系型数据库提供统一访问,由Java语言编写的类和接口组成。
 - 主要的两个包 
  
- java.sql包:提供访问数据库基本的功能
 - javax.sql包:提供扩展功能
 
  - JDBC可以做什么 
  
- 连接到数据库
 - 在Java app中执行SQL语句
 - 处理结果
 
  
 
2.JDBC常用接口
 
- java.sql.Driver:驱动
 - java.sql.Connection:完成对某一指定数据库的连接
 - java.sql.Statement:静态处理块,在一个给定的连接中作为SQL执行声明的容器
 - java.sql.PreparedStatement:预处理块,用于执行预编译的sql声明
 - java.sql.ResultSet:结果集,对于给定声明取得结果的途径
 - java.sql.ResultSetMetaData:结果集元数据
 
 
3.JDBC访问数据库的过程
 
- 驱动管理器——加载jdbc程序
 - 连接数据库——建立于数据库的连接
 - sql语句——发送sql语句
 - 结果集——得到查询结果
 
 
4.代码实现
 
查询sql语句
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCTest {
    public static void main (String[] args) throws Exception {
        
        
       Class.forName ("oracle.jdbc.driver.OracleDriver");
       
        
        
        Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
        
        System.out.println (connection);
        
        
        String sql = "select * from emp";
        
        
        Statement statement = connection.createStatement ();
        
        
        ResultSet resultSet = statement.executeQuery (sql);
        
        
        while(resultSet.next ()){
            int anInt = resultSet.getInt (1);
            System.out.println (anInt);
            String ename = resultSet.getString ("ename");
            System.out.println (ename);
            System.out.println ("-----------------");
        }
        
        statement.close ();
        connection.close ();
    }
}
 
创建表
 
package com.mashibing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreateTable {
    public static void main (String[] args) throws Exception {
        Class.forName ("oracle.jdbc.driver.OracleDriver");
        Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
        Statement statement = connection.createStatement ();
        String sql = "create table psn(id number(10) primary key,name varchar2(10))";
        boolean execute = statement.execute (sql);
        System.out. println (execute);
        statement. close ();
        connection. close ();
    }
}
 
创建自增序列
 
package com.mashibing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreateSeq {
    public static void main (String[] args) throws Exception{
        Class.forName ("oracle.jdbc.driver.OracleDriver");
        Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
        String sql = "create sequence seq_1 increment by 1 start with 1";
        Statement statement = connection.createStatement ();
        boolean execute = statement.execute (sql);
        System.out.println (execute);
        statement.close ();
        connection.close ();
    }
}
 
进行封装
 
package com.mashibing.util;
import java.sql.*;
public class DBUtil {
    public static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
    public static final String USERNAME = "scott";
    public static final String PASSWORD = "tiger";
    static {
        try {
            Class.forName ("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace ();
        }
    }
    
    public static Connection getConnection (){
        try {
            return DriverManager.getConnection (URL,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        return null;
    }
    
    public static void closeConnection (Connection connection){
        if(connection!=null){
            try {
                connection.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
    }
    public static void closeConnection (Connection connection, Statement statement){
        if (statement!=null){
            try {
                statement.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
        if(connection!=null){
            try {
                connection.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
    }
    public static void closeConnection (Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
        if (statement!=null){
            try {
                statement.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
        if(connection!=null){
            try {
                connection.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
        }
    }
}
 
数据访问对象(data access object)
 
接口
 
public interface EmpDao {
    
    public void insert(Emp emp);
    
    public void delete(Emp emp);
    
    public void update(Emp emp);
    
    public Emp getEmpByEmpno(Integer empno);
    public Emp getEmpByEname(String name);
}
 
Emp
 
public class Emp {
    private Integer empno;
    private String ename;
    private String job;
    private Integer mgr;
    private String hiredate;
    private Double sal;
    private Double comm;
    private Integer deptno;
    public Emp() {
    }
    public Emp(Integer empno, String ename, String job,
               Integer mgr, String hiredate, Double sal,
               Double comm, Integer deptno) {
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.mgr = mgr;
        this.hiredate = hiredate;
        this.sal = sal;
        this.comm = comm;
        this.deptno = deptno;
    }
    public Integer getEmpno() {
        return empno;
    }
    public void setEmpno(Integer 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 Integer getMgr() {
        return mgr;
    }
    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }
    public String getHiredate() {
        return hiredate;
    }
    public void setHiredate(String hiredate) {
        this.hiredate = hiredate;
    }
    public Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
    public Double getComm() {
        return comm;
    }
    public void setComm(Double comm) {
        this.comm = comm;
    }
    public Integer getDeptno() {
        return deptno;
    }
    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }
    @Override
    public String toString() {
        return "Emp{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", job='" + job + '\'' +
                ", mrg=" + mgr +
                ", hiredate=" + hiredate +
                ", sal=" + sal +
                ", comm=" + comm +
                ", deptno=" + deptno +
                '}';
    }
}
 
接口实现
 
public class EmpDaoLmp2 implements EmpDao {
    @Override
    public void insert(Emp emp) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = DBUtil.getConnection();
            
            String sql = "insert into emp values(?,?,?,?,?,?,?,?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, emp.getEmpno());
            pstmt.setString(2, emp.getEname());
            pstmt.setString(3,emp.getJob());
            pstmt.setInt(4, emp.getMgr());
            pstmt.setDate(5, new java.sql.Date(new SimpleDateFormat("yyyy-MM-DD").parse(emp.getHiredate()).getTime()));
            pstmt.setDouble(6,emp.getSal());
            pstmt.setDouble(7, emp.getComm());
            pstmt.setInt(8, emp.getDeptno());
            System.out.println(sql);
            int i = pstmt.executeUpdate();
            System.out.println("受影响的行数是:" + i);
        } catch (SQLException | ParseException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection, pstmt);
        }
    }
    @Override
    public void delete(Emp emp) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "delete from emp where empno = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,emp.getEmpno());
            System.out.println(sql);
            int i = statement.executeUpdate();
            System.out.println("受影响的行数是:" + i);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection, statement);
        }
    }
    @Override
    public void update(Emp emp) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "update emp set job = ? where empno = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, emp.getJob());
            statement.setInt(2, emp.getEmpno());
            System.out.println(sql);
            int i = statement.executeUpdate();
            System.out.println("受影响的行数为:" + i);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection, statement);
        }
    }
    @Override
    public Emp getEmpByEmpno(Integer empno) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        Emp emp = null;
        try {
            connection = DBUtil.getConnection();
            statement = connection.createStatement();
            String sql = "select * from emp where empno = " + empno;
            System.out.println(sql);
            resultSet = statement.executeQuery(sql);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            while (resultSet.next()) {
                emp = new Emp(resultSet.getInt("empno"), resultSet.getString("ename"),resultSet.getString("job"),
                        resultSet.getInt("mgr"), sdf.format(resultSet.getDate("hiredate")), resultSet.getDouble("sal"),
                        resultSet.getDouble("comm"), resultSet.getInt("deptno"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection,statement,resultSet);
        }
        return emp;
    }
    @Override
    public Emp getEmpByEname(String name) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet resultSet = null;
        Emp emp = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from emp where ename = ?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, name);
            System.out.println(sql);
            resultSet = pstmt.executeQuery();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            while (resultSet.next()) {
                emp = new Emp(resultSet.getInt("empno"), resultSet.getString("ename"), resultSet.getString("job"),
                        resultSet.getInt("mgr"), sdf.format(resultSet.getDate("hiredate")), resultSet.getDouble("sal"),
                        resultSet.getDouble("comm"), resultSet.getInt("deptno"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection, pstmt, resultSet);
        }
        return emp;
    }
    public static void main(String[] args) {
        EmpDao empDao = new EmpDaoLmp2();
        Emp emp = new Emp(3333,"lala","ooo",1111,"2019-11-09",1500.0,500.0,10);
        empDao.update(emp);
        
    }
}
 
批量提交
 
public class BatchDaoImpl {
    public static void main(String[] args) {
        insertBatch();
    }
    public static void insertBatch() {
        Connection connection = DBUtil.getConnection();
        PreparedStatement pstmt = null;
        String sql = "insert into emp(empno, ename) values(?,?)";
        try {
            pstmt = connection.prepareStatement(sql);
            for (int i = 0; i < 100; i++) {
                pstmt.setInt(1, i);
                pstmt.setString(2, "lx" + i);
                pstmt.addBatch();
            }
            int[] ints = pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection, pstmt);
        }
    }