JDBC初识

1. JDBC介绍

Java Database Connectivity
Java规定的数据库连接接口,SUN公司提供的,为了简化程序员操作数据库的过程。
   SUN公司要求数据库提供商,按照JDBC API接口规范,完成对应Java程序的数据连接操作,规范Jar包,并且提供对应的操作方法。

JDBC接口中核心的内容
   java.sql.

   javax.sql.
**

2. JDBC连接数据库所需的必要条件

cmd > mysql -hlocalhost -uroot -p123456

1. 明确连接使用的数据库是MySQL数据库
2. 明确当前数据库的主机地址,IP地址,域名,localhost表示本地
3. -uroot 用户名
4. -p123456 对应用户名密码

JDBC连接数据库也是需要这四个条件的
1. 确定连接的数据库所在网络地址和对应操作哪一个数据库
   这里使用一个符合JDBC规范的URL
   URL jdbc:mysql://localhost:3306/nzgp2001
2. 用户名 user root
3. 密码 password 123456

URL
含义
    jdbc目前操作数据库的主协议
   mysql子协议
    localhost 数据库服务器所在的网路偶地址
    3306 数据库默认端口号
   nzgp2001 当前URL连接操作对应数据库是哪一个

JDBC是第三方提供的内容
获取对应的Jar
   mysql-connector-java-5.1.47.jar
   从官网获取对应的Jar包
   mvnrepository Maven查询网址

3. JDBC连接MySQL数据库

3.1 操作流程

1. 导入Jar包
    在项目根目录创建lib目录,放入对应jar包,引入依赖
2. 加载驱动
   Java程序只是规定了接口规范,但是没有实现
    数据库连接需要使用JDBC对应驱动
3. 准备必要参数连接数据库
4. 获取数据库连接
5. 关闭资源

3.2 数据库连接演示代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * JDBC连接数据库操作,获取数据库连接方式
 *
 * @author Anonymous 2020/3/23 15:51
 */
public class Demo1 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        /*
        1. 加载驱动
         */
        Class.forName("com.mysql.jdbc.Driver");

        /*
        2. 准备必要的数据
         */
        String url = "jdbc:mysql://localhost:3306/nzgp2001?useSSL=true";
        String user = "root";
        String password = "123456";

        /*
         3. 获取数据库连接
         */
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);

        /*
        4. 关闭资源
         */
        connection.close();

    }
}

3.3 数据库驱动加载过程

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    //
    // Register ourselves with the DriverManager
    // 在.class文件加载到内存时运行,并且有且只执行一次
    // 代码初始化过程!!!
    static {
        try {
            // DriverManager驱动管理器注册了当前com.mysql.jdbc.Driver
            // 相对于当前Java程序拥有了连接MySQL数据库的必要的驱动条件
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

    /**
     * Construct a new driver and register it with DriverManager
     * 
     * @throws SQLException
     *             if a database error occurs.
     */
    public Driver() throws SQLException {
        // Required for Class.forName().newInstance()
    }
}

4. JDBC核心API[能记住最好,记不住拉倒]

class java.sql.DriverManager 驱动管理类
--| static java.sql.Connection getConnection(String url, String user, String password);
/*
	这里是根据听的数据库连接URL,对应的user用户名和password密码,获取数据库连接对象
*/

interface java.sql.Connection 数据库连接接口
--| java.sql.Statement createStatement();
/*
	获取数据库SQL语句搬运工对象,从Java程序搬运SQL语句到数据库中,同时Statement也是一个资源对象。
*/
--| java.sql.PreparedStatement prepareStatement(String sql);
/*
	获取数据库SQL语句【预处理】搬运工对象,Java程序的SQL语句,在创建PreparedStatement对象时,将SQL语句交给数据库预处理操作,可以解决一定的【SQL语句注入问题】,同时提高一定的效率,PreparedStatement也是一个资源对象
*/

interface java.sql.Statement 数据库SQL语句搬运工对象
--| int executeUpdate(String sql);
/*
	执行数据库修改数据,insert,update,delete...,返回值类型是int类型,是当前SQL语句搬运到数据库执行之后,数据库运行对于当前操作受到影响的行数
	2 rows affected in 5 ms
*/
--| java.sql.ResultSet executeQuery(String sql);
/*
	执行数据库查询语句,select操作,执行的结果是一个java.sql.ResultSet,结果集对象,当前操作返回值never null
*/

interface java.sql.PreparedStatement 数据库SQL语句【预处理】搬运工对象
    PreparedStatement extends java.sql.Statement
--| int executeUpdate();
/*
	执行数据库修改操作,insert,update,delete...处理的SQL语句是在创建PreparedStatement对象过程预处理的SQL语句,并且返回值是int类型, 为当前操作对于数据表中收到影响的行数
*/
--| java.sql.ResultSet executeQuery();
/*
	执行数据库查询语句,select操作,的SQL语句是在创建PreparedStatement对象过程预处理的SQL语句,执行的结果是一个java.sql.ResultSet,结果集对象,当前操作返回值never null
*/
--| setXXX(int index, XXX value)
/*
	PreparedStatement预处理的SQL语句是可以带有参数的,这里是对于SQL语句参数进行赋值操作,这里有指定的操作下标,和对应的数据,数据类型繁多
*/
    
interface java.sql.ResultSet 数据库结果集接口
--|XXX getXXX(int columnIndex);
/*
	根据查询结果中,字段所处的位置下标获取对应数据,XXX是指定类型
*/
--|XXX getXXX(String fieldName);
/*
	根据查询结果中,字段所处的字段名获取对应数据,XXX是指定类型
*/
--| boolean next();
/*
	判断当前查询结果集中是否还有可以键遍历操作的数据,如果没有。或则当前结果集中是无数据情况 Empty Set,直接返回fasle
*/

5 Statement操作SQL语句

5.1 Statement插入SQL数据操作

这里有一个nzgp2001数据库,并且有个user表,表中有三个字段,id,userName,password

@Test
public void testInsert() {
    Statement statement = null;
    Connection connection = null;
    try {
        // 1. 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2. 准备必要的连接数据
        String url = "jdbc:mysql://localhost:3306/nzgp2001?useSSL=true";
        String user = "root";
        String password = "123456";
        //3. 获取数据库连接
        connection = DriverManager.getConnection(url, user, password);
        // 4. 获取Statement对象
        statement = connection.createStatement();
        // 5. 准备SQL语句
        String sql = "insert into nzgp2001.user(userName, password) value ('嘟嘟', '123456')";
        // 6. 执行SQL语句
        int affectedRows = statement.executeUpdate(sql);
        System.out.println("affectedRows:" + affectedRows);
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    } finally {
        // 7. 关闭资源
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

5.2 Statement修改SQL数据操作

@Test
public void testUpdate() {
    Statement statement = null;
    Connection connection = null;
    try {
        // 1. 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2. 准备必要的连接数据
        String url = "jdbc:mysql://localhost:3306/nzgp2001?useSSL=true";
        String user = "root";
        String password = "123456";
        //3. 获取数据库连接
        connection = DriverManager.getConnection(url, user, password);
        // 4. 获取Statement对象
        statement = connection.createStatement();
        // 5. 准备SQL语句
        String sql = "update nzgp2001.user set userName ='滴滴' where id = 1";
        // 6. 执行SQL语句
        int affectedRows = statement.executeUpdate(sql);
        System.out.println("affectedRows:" + affectedRows);
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    } finally {
        // 7. 关闭资源
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

5.3 Statement删除SQL数据操作

@Test
public void testDelete() {
    Statement statement = null;
    Connection connection = null;
    try {
        // 1. 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2. 准备必要的连接数据
        String url = "jdbc:mysql://localhost:3306/nzgp2001?useSSL=true";
        String user = "root";
        String password = "123456";
        //3. 获取数据库连接
        connection = DriverManager.getConnection(url, user, password);
        // 4. 获取Statement对象
        statement = connection.createStatement();
        // 5. 准备SQL语句
        String sql = "delete from user where id > 2";
        // 6. 执行SQL语句
        int affectedRows = statement.executeUpdate(sql);
        System.out.println("affectedRows:" + affectedRows);
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    } finally {
        // 7. 关闭资源
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
发布了31 篇原创文章 · 获赞 72 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44945658/article/details/105054652