JDBC的简介及应用

​ Java程序访问数据库的标准接口

一、简单了解一下java访问数据库的流程

使用Java程序访问数据库时,Java代码并不是直接通过TCP连接去访问数据库,而是通过JDBC接口来访问,而JDBC接口则通过JDBC驱动来实现真正对数据库的访问。

┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐

│  ┌───────────────┐  │
   │   Java App    │
│  └───────────────┘  │
           │
│          ▼          │
   ┌───────────────┐
│  │JDBC Interface │<─┼─── JDK
   └───────────────┘
│          │          │
           ▼
│  ┌───────────────┐  │
   │  JDBC Driver  │<───── Vendor
│  └───────────────┘  │
           │
└ ─ ─ ─ ─ ─│─ ─ ─ ─ ─ ┘
           ▼
   ┌───────────────┐
   │   Database    │
   └───────────────┘

实际上,一个MySQL的JDBC的驱动就是一个jar包,它本身也是纯Java编写的。我们自己编写的代码只需要引用Java标准库提供的java.sql包下面的相关接口,由此再间接地通过MySQL驱动的jar包通过网络访问MySQL服务器,所有复杂的网络通讯都被封装到JDBC驱动中,因此,Java程序本身只需要引入一个MySQL驱动的jar包就可以正常访问MySQL服务器:

┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
   ┌───────────────┐
│  │   App.class   │  │
   └───────────────┘
│          │          │
           ▼
│  ┌───────────────┐  │
   │  java.sql.*   │
│  └───────────────┘  │
           │
│          ▼          │
   ┌───────────────┐     TCP    ┌───────────────┐
│  │ mysql-xxx.jar │──┼────────>│     MySQL     │
   └───────────────┘            └───────────────┘
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
          JVM

二、java操作oracle数据库

1.基本流程

JDBC基本流程:
    把oracle实现jar包拿到项目下  add as lib..
    1.加载驱动  (选择数据库)
    2.建立连接 Connection (与数据库之间建立连接)
    3.准备sql
    4.封装处理块,发送sql
    5.得到结果集
    6.处理结果
    7.关闭资源
public class Class01_JDBC {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动  (选择数据库)
        Class.forName("oracle.jdbc.driver.OracleDriver");

        //2.建立连接 Connection (与数据库之间建立连接)
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
                "SCOTT",
                "TIGER");

        //3.准备sql
        String sql = "select * from dept";

        //4.封装处理块,发送sql
        Statement state = conn.createStatement();

        //5.得到结果集
        ResultSet realut = state.executeQuery(sql);

        //6.处理结果
        while (realut.next()){
            int deptno = realut.getInt(1);
            String dname = realut.getString(2);
            String loc = realut.getString(3);
            System.out.println(deptno+"--->"+dname+"--->"+loc);
        }
        //7.关闭资源
        realut.close();
        state.close();
        conn.close();
    }
}

附:对此流程的优化(异常,软编码)

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
username=SCOTT
password=TIGER
package jdbc01;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/*
   优化:
    1.异常 捕获
    2.通过配置文件实现软编码
 */
public class Class02_JDBC {
    public static void main(String[] args) {
        //构建 properties对象
        Properties pro = new Properties();
        try {
            pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properies"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //1.加载驱动(选择数据库)
        try {
            Class.forName(pro.getProperty("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //建立连接 Connection (与数据库之间建立连接)
        Connection conn = null;
        Statement state = null;
        ResultSet result = null;

        try {
            conn = DriverManager.getConnection(
                    pro.getProperty("url"),
                    pro.getProperty("username"),
                    pro.getProperty("password")
            );

            //3.准备sql
            String sql = "select * from dept";
            //4.封装处理块
            state = conn.createStatement();
            //5.发送sql,得到结果集
            result = state.executeQuery(sql);
            //6.处理结果
            while (result.next()){
                int deptno = result.getInt(1);
                String dname = result.getString(2);
                String loc = result.getString(3);
                System.out.println(deptno+"--->"+dname+"--->"+loc);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //7.关闭资源
            if(result!=null){
                try {
                    result.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(state!=null){
                try {
                    state.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }


    }
}

连接jdbc的流程进行简单的封装

public class DBUtils {
    /*
    JDBC工具类
        1.加载驱动
        2.获取连接
        3.关闭资源
 */
        private static Properties pro = new Properties();
        static{
            //1.加载驱动
            //构建 properties对象
            try {
                pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            //加载驱动  (选择数据库)
            try {
                Class.forName(pro.getProperty("driver"));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        //2.获取连接
        public static Connection getConnection() throws SQLException {
            Connection conn = null;
            conn = DriverManager.getConnection(
                    pro.getProperty("url"),
                    pro.getProperty("username"),
                    pro.getProperty("password")
            );
            return conn;
        }

        //3.关闭资源
        public static void close(ResultSet result, Statement state, Connection conn){
            if(result!= null){
                try {
                    result.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(state!=null){
                try {
                    state.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        public static void close(Statement state,Connection conn){
            close(null,state,conn);
        }

}
2)主要功能举例实现
对用户进行操作
    1.注册用户
    2.登录用户
    3.修改用户信息
    4.注销用户
public class Class03_User {
    public static void main(String[] args) {

    }

    public static  boolean update(String username,String password){
        //1.获取连接
        Connection conn = null;
        PreparedStatement ps = null;
        boolean flag = false;

        try {
            conn = DBUtils.getConnection();

            //设置手动提交
            conn.setAutoCommit(false);

            //2.构建预处理块
            ps = conn.prepareStatement("update t_user set password=? where username=?");
            //3.为?赋值
            ps.setObject(1,password);
            ps.setObject(2,username);

            //4.执行,得到影响行数
            int rows = ps.executeUpdate();

            //5.判断
            if(rows>0){
                flag = true;
                conn.commit(); //提交
            }else{
                conn.rollback(); //回滚
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return flag;
    }
}

数据库通用访问对象封装

public class BaseDao {
    /**
     * 增删改
     * @param sql  要执行的sql语句
     * @param args 为?赋值的实参
     * @return 成功与否
     */
    public boolean update(String sql,Object[] args){
        //1.获取连接
        Connection conn = null;
        PreparedStatement ps = null;
        boolean flag = false;
        try {
            conn = DBUtils.getConnection();
            //2.构建预处理块
            ps = conn.prepareStatement(sql);
            //3.为?赋值
            if(args!=null && args.length!=0){
                for(int i=0;i<=args.length-1;i++){
                    ps.setObject(i+1,args[i]);
                }
            }
            //4.执行sql,得到相应行数
            int rows = ps.executeUpdate();

            //5.对相应行数判断结果
            if(rows>0){
                flag = true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtils.close(ps,conn);
        }
        return flag;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值