JDBC

时间:2019-09-03
本文章向大家介绍JDBC,主要包括JDBC使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

第一章 JDBC的快速入门

1.1 概念

  • java database connection,Java数据库连接(用Java语言操作数据库)。

1.2 JDBC的本质

  • 官方(SUN公司)定义了操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动的jar包。我们可以使用这套接口(JDBC)编程,真正执行代码的是驱动jar包中的实现类。

1.3 快速入门

  • 驱动的maven坐标:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>
  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " select id,name from employee ";
        //获取执行SQL的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            int id = rs.getInt(1);
            String name = rs.getString(2);
            System.out.println(id);
            System.out.println(name);
        }
        //释放资源
        if (connection != null) {
            connection.close();
        }
        
    }
}

第二章 JDBC各个类详解

2.1 DriverManager

  • 驱动管理对象。
  • 作用:
  • ①注册驱动。
public static synchronized void registerDriver(java.sql.Driver driver){}
  • ②获取数据库连接对象。
public static Connection getConnection(String url,
        String user, String password) throws SQLException {}

2.2 Connection

  • 数据库连接对象。
  • 作用:
  • ①获取执行SQL的对象。
    • 获取Statement对象:
Statement createStatement() throws SQLException;
    • 获取PreparedStatement对象:
PreparedStatement prepareStatement(String sql);
  • ②管理事务。
    • 开启或关闭自动提交。  
void setAutoCommit(boolean autoCommit) throws SQLException;
    • 提交事务。  
void commit() throws SQLException;
    • 回滚事务。  
void rollback() throws SQLException;

2.3 Statement

  • 执行静态SQL的对象。
  • 执行DML或DDL语句:
int executeUpdate(String sql) throws SQLException;
  • 执行DQL语句:
ResultSet executeQuery(String sql) throws SQLException;

2.4 ResultSet

  • 结果集对象,封装查询结果。
  • 游标向下移动一行:
boolean next() throws SQLException;
  • 获取数据:
Xxx getXxx(int columnIndex) throws SQLException; // cloumnIndex代表列的编号,从1开始
Xxx getXxx(String columnLabel) throws SQLException; //cloumnLable代表列的名称 

2.5 PreparedStatement

  • 执行预编译SQL的对象。
  • 可以用来解决SQL注入问题。
  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " select id ,`name` from employee where id = ? ";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1, 1);

        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            System.out.println("id:" + id + ",name=" + name);
        }

        if (connection != null) {
            connection.close();
        }


    }
}

第三章 JDBC之CRUD

3.1 增加

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " insert into employee (name) values ('zhangsan') ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

3.2 更新

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " update employee set name = 'xuweiwei' where id = 1 ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

3.3 删除

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " delete from employee where id = 5 ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

3.4 DDL

  • 示例:
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
        //定义SQL语句
        String sql = " create table student(id int primary key ,name varchar (255)) ";

        Statement statement = connection.createStatement();

        int count = statement.executeUpdate(sql);

        System.out.println(count);

        if (connection != null) {
            connection.close();
        }
    }
}

第四章 事务管理

4.1 概述

  • 一个包含多个步骤的业务操作。如果这个业务操作被事务管理,那么这多个步骤要么同时成功,要么同时失败。

4.2 步骤

  • 开启事务。
  • 提交事务。
  • 回滚事务。

4.3 应用示例

  • 示例:
CREATE TABLE `account`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `money` double NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
)
INSERT INTO `account` VALUES (1, '张三', 1000);
INSERT INTO `account` VALUES (2, '李四', 1000);
package com.sunxiaping.jdbc;

import java.sql.*;

public class QuickStart {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            String user = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);

            connection.setAutoCommit(false);

            String sql = " update account set money = money - 500 where id = ? ";

            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 1);

            int count = preparedStatement.executeUpdate();

            sql = " update account set money = money + 500 where id = ? ";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 2);

            //设置异常
            int num = 1 / 0 ;

            count = preparedStatement.executeUpdate();

            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != connection) {
                try {
                    connection.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }

        } finally {
            if (null != preparedStatement) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (null != connection) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

第五章 数据库连接池

5.1 概述

  • 数据库连接池就是一个容器(集合),存放数据库连接的容器。
  • 当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库的时候,从容器中获取连接对象,当用户访问完之后,会将连接对象归还给容器。

5.2 好处

第六章 JDBC Template

原文地址:https://www.cnblogs.com/xuweiweiwoaini/p/11456092.html