MySQL攻略 - JDBC程序原理、Mysql连接5种方式、与一些基本使用的语法介绍和练习

JDBC概述

基本介绍

  1. JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题。

  2. Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。

JDBC的基本原理(图)

请添加图片描述

案例模拟

Java提供接口

package com.taotao.jdbc.myjdbc;

/**
 * Create By 刘鸿涛
 * 2022/2/21 12:41
 * 模拟Java接口
 */
public interface JdbcInterface {
    //连接
    public Object getConnection();
    //crud
    public void crud();
    //关闭连接
    public void close();
}

Mysql厂商接口实现类

package com.taotao.jdbc.myjdbc;

/**
 * Create By 刘鸿涛
 * 2022/2/21 12:43
 * mysql 数据库实现了jdbc接口(模拟)【mysql 厂商实现此接口】
 */
public class MysqlJdbcImplements implements JdbcInterface{

    @Override
    public Object getConnection() {
        System.out.println("得到 mysql 的连接");
        return null;
    }

    @Override
    public void crud() {
        System.out.println("完成 mysql 增删改查");
    }

    @Override
    public void close() {
        System.out.println("关闭 mysql 连接");
    }
}

Oracle接口实现类

package com.taotao.jdbc.myjdbc;

/**
 * Create By 刘鸿涛
 * 2022/2/21 12:51
 * 模拟oracle 数据库实现 jdbc
 */
public class OracleJdbcImplements implements JdbcInterface{

    @Override
    public Object getConnection() {
        System.out.println("得到 oracle 的连接");
        return null;
    }

    @Override
    public void crud() {
        System.out.println("完成 oracle 增删改查");
    }

    @Override
    public void close() {
        System.out.println("关闭 oracle 的连接");
    }
}

使用演示

package com.taotao.jdbc.myjdbc;

/**
 * Create By 刘鸿涛
 * 2022/2/21 12:48
 */
public class TextJDBC {
    public static void main(String[] args) {
        //完成对mysql的操作
        JdbcInterface jdbcInterface = new MysqlJdbcImplements();

        jdbcInterface.getConnection();      //通过接口来调用实现类【动态绑定】
        jdbcInterface.crud();
        jdbcInterface.close();

        JdbcInterface jdbcInterface1 = new OracleJdbcImplements();
        jdbcInterface1.getConnection();
        jdbcInterface1.crud();
        jdbcInterface1.close();

    }
}

如果Java直接访问数据库(示意图)

请添加图片描述

JDBC带来的好处

JDBC是Java提供一套用于数据库操作的接口API, Java程序员只需要面向这套接口编程即可。不同的数据库厂商,需要针对这套接口,提供不同实现。

JDBC API

JDBC API是一系列的接口,它统一和规范了应用程序与数据库的连接、执行SQL语句,并得到返回结果等各类操作,相关类和接口在java.sql与javax.sql包中

请添加图片描述

java.sql包

请添加图片描述

javax.sql包

请添加图片描述

JDBC程序编写步骤

1.注册驱动

加载Driver 类

2.获取连接

得到Connection

3.执行增删改查

发送SQL 给mysql执行

4.释放资源

关闭连接

案例演示

建立表

create table actor(
	id int primary key auto_increment,
    name varchar(32) not null default' ',
    sex char(1) not null default '女',
    borndate datetime,
    phone varchar(12)
);

建立目录libs

导入jar文件

添加为库

请添加图片描述

新建对象,拿到driver

请添加图片描述

代码演示

package com.taotao.jdbc;

import com.mysql.cj.jdbc.Driver;

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

/**
 * Create By 刘鸿涛
 * 2022/2/21 16:14
 * 这是第一个Jdbc 程序,完成简单的操作
 */
public class Jdbc01 {
    public static void main(String[] args) throws SQLException {
        //前置工作:在项目下创建一个文件夹 比如 libs
        //将 mysql.jar 拷贝到该目录下,点击 add to project...加入到项目中

        //1.注册驱动
        Driver driver = new Driver();   //创建driver对象

        //2.得到连接
        // (1)jdbc:mysql://规定好表示协议,通过jdbc的方式连接mysql
        // (2)localhost 主机,可以使用ip地址
        // (3)3306 表示mysql监听的端口
        // (4)taotao_db01 连接到mysql dbms的哪个数据库
        // (5) mysql的连接本质就是前面学过的socket连接
        String url = "jdbc:mysql://localhost:3306/taotao_db01";
        //将 用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        //说明 user 和 password 是规定好,后面的值根据实际情况写
        properties.setProperty("user","root");  //用户
        properties.setProperty("password","12345");   //密码

        Connection connect = driver.connect(url, properties);

        //3.执行sql
        String sql = "insert into actor values(null,'刘德华','男','1970-11-11','110')";
        //用于执行静态SQL语句并返回其生成的结果的对象
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql);    //如果是 dml 语句,返回的就是影响行数

        System.out.println(rows > 0 ? "成功":"失败");

        //4.关闭连接资源
        statement.close();
        connect.close();
    }
}

作图分析(图)

请添加图片描述

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

方式一(Driver)

    @Test
    public void connect01() throws SQLException {
        Driver driver = new Driver();   //创建driver对象
        String url = "jdbc:mysql://localhost:3306/taotao_db01";
        //将 用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        //说明 user 和 和 password 是规定好,后面的值根据实际情况写
        properties.setProperty("user","root");  //用户
        properties.setProperty("password","12345");    //密码
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }

结论

灵活性不高

方式二(反射)

    @Test
    public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        //使用反射加载Driver类,动态加载,更加灵活
        Class<?> driverClass = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver)driverClass.newInstance();

        String url = "jdbc:mysql://localhost:3306/taotao_db01";
        //将 用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        //说明 user 和 和 password 是规定好,后面的值根据实际情况写
        properties.setProperty("user","root");  //用户
        properties.setProperty("password","12345");    //密码

        Connection connect = driver.connect(url, properties);
        System.out.println("方式二" + connect);
    }

结论

更加灵活

方式三(DriverManager)

    //方式3
    //使用DriverManager 替代Diver 进行统一管理
    @Test
    public void connect03() 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/taotao_db01";
        String user = "root";
        String password = "12345";

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

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println("第三种方式" + connection);

结论

结构更清晰

方式四(代码简化)

    //方式4:使用Class.forName 自动完成注册驱动,简化代码
	//这种方式获取连接是使用的最多的,推荐使用
    @Test
    public void connect04() throws ClassNotFoundException, SQLException {
        //使用反射加载了Driver类
        //在加载 Driver类时,底层完成注册
        /*	源码:1.静态代码块,在类加载时,会执行一次
        		2. DriverManager.registerDriver(new Driver());
        		3. 因此注册driver的工作已经完成
        	static {
        		try {
        			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/taotao_db01";
        String user = "root";
        String password = "12345";

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println("第四种方式 " + connection);
    }

结论

Driver类底层有静态代码块,通过DriverManger,自动完成Driver的注册

方式五(读取配置文件)

    //方式5,在方式4的基础上改进,增加配置文件,让连接mysql更加灵活
    @Test
    public void connection5() throws IOException, ClassNotFoundException, SQLException {

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

        Class.forName("com.mysql.cj.jdbc.Driver"); //建议写上,可以不写

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println("方式5" + connection);
    }

mysql.properties配置文件

user=root
password=12345
url=jdbc:mysql://localhost:3306/taotao_db01
driver=com.mysql.cj.jdbc.Driver

结论

第五种方式,通过properties类读取配置文件,得到相应的值,使用起来更加灵活

提示

  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.jdbc”)

课堂练习(使用方式五实现)

  1. 创建 actor 表(未实现)
  2. 使用jdbc 添加 3条数据
  3. 修改id = 1的记录,将name改成 你自己的名字
  4. 删除id = 3 的记录
package com.taotao.homework;

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

/**
 * Create By 刘鸿涛
 * 2022/2/28 13:16
 */
public class Homework01 {
    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        create();
        update();
        delete();
    }

    @SuppressWarnings({"all"})
    public static void create() throws SQLException, ClassNotFoundException, IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));

        //获取账号密码
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        //获取驱动
        String url = properties.getProperty("url");

        //1.加载Driver类
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2.连接SQL
        Connection connection = DriverManager.getConnection(url, user, password);

        //3.得到statement,然后执行增删改查
        Statement statement = connection.createStatement();

        //4.组织SQL
        String sql = "insert into actor values(null,'涛涛','男','1970-11-11','110'),(null,'刘刘','男','1980-12-12','120'),(null,'鸿鸿','女','1990-1-1','119')";

        int rows = statement.executeUpdate(sql);


        System.out.println(rows > 0 ?"成功":"失败");



        //5.关闭连接资源
        statement.close();
        connection.close();


    }

    @SuppressWarnings({"all"})
    public static void update() throws IOException, ClassNotFoundException, SQLException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));

        //获取账号密码
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        //获取驱动
        String url = properties.getProperty("url");

        //1.加载Driver类
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2.连接SQL
        Connection connection = DriverManager.getConnection(url, user, password);

        //3.得到statement,然后执行增删改查
        Statement statement = connection.createStatement();

        //4.组织SQL
        String sql = "update actor set name = '刘鸿涛' where id =1";

        int rows = statement.executeUpdate(sql);


        System.out.println(rows > 0 ?"成功":"失败");



        //5.关闭连接资源
        statement.close();
        connection.close();
    }

    @SuppressWarnings({"all"})
    public static void delete() throws IOException, ClassNotFoundException, SQLException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));

        //获取账号密码
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        //获取驱动
        String url = properties.getProperty("url");

        //1.加载Driver类
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2.连接SQL
        Connection connection = DriverManager.getConnection(url, user, password);

        //3.得到statement,然后执行增删改查
        Statement statement = connection.createStatement();

        //4.组织SQL
        String sql = "delete from actor where id = 3";

        int rows = statement.executeUpdate(sql);


        System.out.println(rows > 0 ?"成功":"失败");



        //5.关闭连接资源
        statement.close();
        connection.close();
    }
}

ResultSet[结果集]

基本介绍

  1. 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
  2. ResultSet对象保持一个光标指向当前的数据行。最初,光标位于第一行之前
  3. next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集

案例演示select 查询语句

package com.taotao.homewor;

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

/**
 * Create By 刘鸿涛
 * 2022/2/28 13:16
 */
public class Homework01 {
    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        createMethod();
    }

    @SuppressWarnings({"all"})
    public static void createMethod() throws SQLException, ClassNotFoundException, IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));

        //获取账号密码
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        //获取驱动
        String url = properties.getProperty("url");

        //1.加载Driver类
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2.连接SQL
        Connection connection = DriverManager.getConnection(url, user, password);

        //3.得到statement,然后执行增删改查
        Statement statement = connection.createStatement();

        //4.组织SQL
        String sql = "select id,name,sex,borndate,phone from actor";
        //执行给定的SQL与语句,该语句返回单个 ResultSet对象

        /*
        *
        * +----+--------+-----+---------------------+-------+
        | id | name   | sex | borndate            | phone |
        +----+--------+-----+---------------------+-------+
        |  1 | 刘德华 | 男  | 1970-11-11 00:00:00 | 110   |
        |  2 | 刘德华 | 男  | 1970-11-11 00:00:00 | 110   |
        |  3 | 刘德华 | 男  | 1970-11-11 00:00:00 | 110   |
        |  4 | 刘德华 | 男  | 1970-11-11 00:00:00 | 110   |
        |  5 | jack   | 男  | 1990-11-11 00:00:00 | 112   |
        +----+--------+-----+---------------------+-------+
        * */
        ResultSet resultSet = statement.executeQuery(sql);

        //5.使用while取出数据
        while (resultSet.next()){   //让光标向后移动,如果没有更多行,则返回false
            int id = resultSet.getInt(1);    //获取该行的第一列数据
            String name = resultSet.getString(2);   //获取该行的第二列
            String sex = resultSet.getString(3);
            Date date = resultSet.getDate(4);
            String phone = resultSet.getString(5);
            System.out.println(id + "\t" + name + "\t" + sex + "\t" + date + "\t" + phone);

            
        }


        //6.关闭连接资源
        resultSet.close();
        statement.close();
        connection.close();


    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼鬼骑士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值