JDBC和连接池

基本介绍

  1. JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题。
  2. Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。
  3. JDBC 原理图
    在这里插入图片描述
  4. JDBC 的好处?
    JDBC是Java提供一套用于数据库操作的接口APl,Java程序员只需要面向这套接口编程即可。不同的数据库厂商,需要针对这套接口,提供不同实现。
  5. JDBC API是一系列的接口,它统一和规范了应用程序与数据库的连接、执行SQL语句,并到得到返回结果等各类操作,相关类和接口在 java.sqljavax.sql 包中

第一个 JDBC 程序

在这里插入图片描述

编写步骤
  1. 注册驱动 – 加载 Driver
  2. 获取连接 – 得到 Connection
  3. 执行增删改查 – 发送 SQLmysql 执行
  4. 释放资源 – 关闭相关连接


package Test;

import com.mysql.cj.jdbc.Driver;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author: Gin
 * @Description:
 * @Modified By: Gin
 * @Date: Created in 16:15 2021/9/13
 */
public class Test5 {
    public static void main(String[] args) throws SQLException {

        // 前置工作:在项目下创建文件夹,如 libs,把 mysql.jar 复制到 libs 下,右键 Add as Library
        // 1. 注册驱动  创建 Driver 对象,  com.mysql.cj.jdbc 包下的 Driver
        Driver driver = new Driver();

        // 2. 得到连接
        // jdbc:mysql://   -- 规定好的协议,通过 jdbc 的方式连接 MySQL
        // localhost:      -- 主机,也可以是 ip 地址
        // 3306            -- 表示 MySQL 监听的端口号
        // db2             -- 表示连接到哪个数据库
        String url = "jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        // 将用户名和密码存放到 Properties 对象中
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection conn = driver.connect(url, properties);

        // 3. 执行 sql
        String sql = "insert into actor values(null, 'Vodka', '男', '1977-10-10', '222')";
        Statement st = conn.createStatement();
        Integer rows = st.executeUpdate(sql);
        System.out.println(rows > 0 ? "执行 SQL 成功!" : "执行 SQL 失败!");

        // 4. 关闭连接
        st.close();
        conn.close();

    }
}



获取数据库连接的 5 种方式



package Test;

import com.mysql.cj.jdbc.Driver;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author: Gin
 * @Description:
 * @Modified By: Gin
 * @Date: Created in 16:55 2021/9/13
 */
public class Test6 {

    // 方式 1
    @Test
    public void connection1() throws SQLException {
        // 注册驱动  创建 Driver 对象
        Driver driver = new com.mysql.cj.jdbc.Driver();
        String url = "jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        // 将用户名和密码存放到 Properties 对象中
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection conn = driver.connect(url, properties);
        System.out.println(conn);
    }

    // 方式 2
    @Test
    public void connection2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        // 通过反射机制加载 Driver 类。动态加载,更加灵活,减少依赖性
        Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver)aClass.newInstance();

        String url = "jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        // 将用户名和密码存放到 Properties 对象中
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "root");
        Connection conn = driver.connect(url, properties);
        System.out.println(conn);
    }

    // 方式 3
    @Test
    public void connection3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        // 反射加载 Driver 类
        Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) aClass.newInstance();

        // 创建 url、user、password
        String url = "jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "root";

        // 注册驱动
        DriverManager.registerDriver(driver);

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

    // 方式 4 :使用 Class.forName() 自动完成注册驱动,简化代码
    // 推荐使用 方式 4
    @Test
    public void connection4() throws ClassNotFoundException, SQLException {
        // 反射加载 Driver 类
        /*
            com.mysql.cj.jdbc.Driver 源码:
            // 1. 静态代码块,在类加载时会执行一次
            // 2. DriverManager.registerDriver(new Driver());   --  完成了 Driver 对象的创建和注册
            static {
                try {
                    // 此处完成了 Driver 对象的创建和注册
                    DriverManager.registerDriver(new Driver());
                } catch (SQLException var1) {
                    throw new RuntimeException("Can't register driver!");
                }
            }

         */
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 创建 url、user、password
        String url = "jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "root";

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);

    }
    // 1. MySQL 驱动 5.1.6 可以无需 CLass.forName(“com.mysql.cj.jdbc.Driver");
    // 2. 从 jdk1.5 以后使用了 jdbc4,不再需要显示调用 Class.forName() 注册驱动而是自动调用驱动
    //    jar 包下 META-INF\services\java.sql.Driver 文本中的类名称去注册
    // 3. 建议还是写上 CLass.forName(“com.mysql.cj.jdbc.Driver"),更加明确

    
    // 方式 5 
    @Test
    public void connection5() throws IOException, ClassNotFoundException, SQLException {

        // 通过 mysql.properties 对象获取配置文件的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相关值
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        // 获取驱动;建议写上
        Class.forName(driver);

        Connection conn = DriverManager.getConnection(url, user, password);

        System.out.println(conn);
    }


}



ResultSet



package Test;

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

/**
 * @Author: Gin
 * @Description:
 * @Modified By: Gin
 * @Date: Created in 20:04 2021/9/13
 */
public class Test7 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {

        // 1. 读配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        // 2. 注册驱动
        Class.forName(driver);

        // 3. 获取连接
        Connection conn = DriverManager.getConnection(url, user, password);

        // 4. 执行增删改查
        String sql = "select id, name, sex, borndate, phone from actor";
        Statement st = conn.createStatement();
        ResultSet resultSet = st.executeQuery(sql);
        while (resultSet.next()){
//            Integer id = resultSet.getInt("id");
//            String name = resultSet.getString("name");
//            String sex = resultSet.getString("sex");
//            String borndate = resultSet.getString("borndate");
//            String phone = resultSet.getString("phone");
            Integer id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String sex = resultSet.getString(3);
            String borndate = resultSet.getString(3);
            String phone = resultSet.getString(4);
            System.out.println(id + '\t' + name + '\t' +sex + '\t' + borndate + '\t' + phone);
        }

        // 5. 关闭连接
        resultSet.close();
        st.close();
        conn.close();

    }
}



在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值