其他分享
首页 > 其他分享> > JDBC

JDBC

作者:互联网

目录

● 简介

● JDBC 的常⽤类和接⼝

● JDBC开发步骤:​​​​​​​

● JDBC接口核心的API

● PreparedStatement(预编译)   vs    Statement:

● 加载mysql-connector-java-5.1.7-bin.jar

● 使用JDBCUtil

●删除、增加、修改


● 简介:

(java DateBase Connective)java 数据连接技术,是由 java 提供的⼀个与平台⽆关的数据库操作标准(是⼀组接⼝的组成),数据库属于资源操作,所以所有的数据库操作最后必须要关闭数据库的连接。

(java DateBase Connective)java 数据连接技术,是由 java 提供的⼀个与平台⽆关的数据库操作标准(是⼀组接⼝的组成),数据库属于资源操作,所以所有的数据库操作最后必须要关闭数据库的连接。 

 ● JDBC 的常⽤类和接⼝:​​​​​​​

驱动管理器获得数据连接:public class DriverManager extends Object
数据库连接接⼝:public interface Connection extends Wrapper, AutoCloseable
⽤来操作静态 SQL 语句:public interface Statement extends Wrapper, AutoCloseable
⽤来操作动态 SQL 语句:public interface PreparedStatement extends Statement
⽤来调⽤储存过程的语句:public interface CallableStatement extends PreparedStatement
结果结合接⼝:public interface ResultSet extends Wrapper, AutoCloseable
结果集元数据:public interface ResultSetMetaData extends Wrapper
数据元数据:public interface DatabaseMetaData extends Wrapper

● JDBC开发步骤:​​​​​​​

1、加载驱动Class.forName("");  

2、获得连接对象Connection

3、写sql语句

4、创建Statement(一艘船)

5、执行sql语句

     (1) 更新类(更改了表里面数据):delete/update/insert     executeUpdate()

           返回值:int,表示你影响的行数

      (2)查询(没有改变表里面数据):  select                              executeQuery()

           返回值:结果集ResultSet

6、关闭连接

● JDBC接口核心的API

|- DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序

            |-registerDriver(driver) : 注册驱动类对象

            |-Connection getConnection(url,user,password); 获取连接对象

|- Connection接口: 表示java程序和数据库的连接对象。

            |- Statement createStatement() : 创建Statement对象

            |- PreparedStatement prepareStatement(String sql) 创建PreparedStatement对象

            |- CallableStatement prepareCall(String sql) 创建CallableStatement对象(调用写好的存储过程)

|- Statement接口: 用于执行静态的sql语句

              |- int executeUpdate(String sql) : 执行静态的更新sql语句

              |- ResultSet executeQuery(String sql) :执行的静态的查询sql语句

|-PreparedStatement接口:用于执行预编译sql语句

              |- int executeUpdate() : 执行预编译的更新sql语句

              |-ResultSet executeQuery() : 执行预编译的查询sql语句

|- ResultSet接口:用于封装查询出来的数据

         |- boolean next() : 将光标移动到下一行

         |-getXX() : 获取列的值

● PreparedStatement(预编译)   vs    Statement:

1、语法不同:

PreparedStatement可以使用预编译的sql,只需要发送一次sql语句,后面只要发送参数即可,公用一个sql语句。

Statement只能使用静态的sql。    delete from student where id=1;

2、效率不同:PreparedStatement使用了sql缓冲区,效率要比Statement高。

3、安全性不同:PreparedStatement可以有效的防止sql注入,而Statement不能防止sql注入。

     @Test
    public void test1() {
        try {
            // 1、加载驱动Class.forName("");
            Class.forName("com.mysql.jdbc.Driver");
            // 2、获得连接对象Connection
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
            // 3、写sql语句
            String sql = "SELECT id,`name`,age,gender FROM student";
            // 4、创建Statement(一艘船)
            Statement statement = connection.createStatement();
            // 5、执行sql语句
            //         (1) 更新类(更改了表里面数据):delete/update/insert         executeUpdate()
            // 返回值:int,表示你影响的行数
            //         (2)查询(没有改变表里面数据):  select                       executeQuery()
            // 返回值:结果集ResultSet
            ResultSet resultSet = statement.executeQuery(sql);
            ArrayList<Student> list = new ArrayList<>();
            // next()方法判断下一行有没有,如果有指向下一行
            while (resultSet.next()) {
                // 每遍历一次循环,就拿出数据库查询结果里面的一行记录,就是一个学生的信息,
                // 就可以封装成一个Student对象
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id, name, age, gender);
                list.add(student);
            }
            for (Student student : list) {
                System.out.println(student);
            }
            // 6、关闭连接
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            // 先打开的后关闭
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        // SELECT id,`name`,age,gender FROM student
        // ArrayList<Student> list
    } 


 @Test
    public void test2() {
        int selectId =15;
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
            String sql = "SELECT id,`name`,age,gender FROM student WHERE id >= ?";
            // PreparedStatement 使用预编译的sql
            statement = connection.prepareStatement(sql);
            // 填上?占位符的值
            statement.setInt(1, selectId);
            System.out.println(statement);
            resultSet = statement.executeQuery();
            ArrayList<Student> list = new ArrayList<>();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id, name, age, gender);
                list.add(student);
            }
            for (Student student : list) {
                System.out.println(student);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 先打开的后关闭
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

 ● 加载mysql-connector-java-5.1.7-bin.jar

 ● 使用JDBCUtil

public class JDBCUtil {

    private JDBCUtil() {
    }

    // 静态代码块  只执行一次,保证这个驱动只加载一次
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static  Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
        return connection;
    }

    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        // 先打开的后关闭
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }



}
  @Test
    public void test3() {
        int selectId =15;
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "SELECT id,`name`,age,gender FROM student WHERE id >= ?";
            // PreparedStatement 使用预编译的sql
            statement = connection.prepareStatement(sql);
            // 填上?占位符的值
            statement.setInt(1, selectId);
            System.out.println(statement);
            resultSet = statement.executeQuery();
            ArrayList<Student> list = new ArrayList<>();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id, name, age, gender);
                list.add(student);
            }
            for (Student student : list) {
                System.out.println(student);
            }
        }  catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
    }

●删除、增加、修改

//删除
 @Test
    public void testDelete() {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "DELETE FROM student WHERE id=?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, 15);
            System.out.println(statement);
            int count = statement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, null);
        }
    }

//增加
    @Test
    public void testInsert() {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "INSERT INTO student(name,age,gender) VALUES (?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, "小张");
            statement.setInt(2, 21);
            statement.setString(3, "男");
            System.out.println(statement);
            int count = statement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, null);
        }
    }

//修改    
    @Test
    public void testUpdate() {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "UPDATE student SET name=?,age=?,gender=? WHERE id=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, "小王");
            statement.setInt(2, 20);
            statement.setString(3, "女");
            statement.setInt(4, 16);
            System.out.println(statement);
            int count = statement.executeUpdate();
            System.out.println("count: " + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, null);
        }
    }

标签:JDBC,throwables,resultSet,connection,statement,sql,null
来源: https://blog.csdn.net/weixin_43890079/article/details/119476497