jdbc知识点和代码块

本文深入探讨了Java JDBC的相关知识点,包括六个基本步骤、数据库连接、处理结果集、防止SQL注入、Statement与PreparedStatement的区别、事务管理、工具类的应用以及乐观锁和悲观锁的概念。内容详实,适合Java开发者学习数据库操作。


jdbc


思路

六个步骤 注册驱动 获取连接 获取数据库操作对象 执行SQL 处理查询结果集 释放资源
localhost 和 127.0.0.1 都是 本机IP地址 每台机器都是 是本机的回送地址 指本地机 一般用来测试使用
连接数据库存数据
大佬总结更为详细

package com.lianxi;


import java.sql.*;

public class JDBCTest01 {
    public static void main(String[] args) {
        Statement statement=null;
        Connection connection=null;
        try {
            //注册驱动
            Driver driver=new com.mysql.cj.jdbc.Driver();//接口   实现类
            DriverManager.registerDriver(driver);//驱动管理器 静态方法
            //获取连接
            String url="jdbc:mysql://127.0.0.1:3306/bjpowernode?serverTimezone=Asia/Shanghai";//协议 IP地址 端口 数据库下的表
            String user="root";
            String password="159357";
             connection=DriverManager.getConnection(url,user,password);//静态方法 返回的是Connection 连接
            System.out.println("数据库连接对象="+connection);
            //获取数据库操作对象,statement 专门执行sql语句
             statement=connection.createStatement();
            //执行sql
            String sql="insert into dept(deptno,dname,loc) values(50,'人事部','北京')";
            int count=statement.executeUpdate(sql);
            System.out.println(count==1?"保存成功":"保存失败");
            //处理查询结果集
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //释放资源 为了保证资源一定释放,在Finally 语句块中关闭资源  并且要遵循从小到大依次关闭 分别对其try  ...catch
           if(statement!=null){
               try {
                   statement.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

写sql语句的时候不需要写分号,会报错

第二种写法

package com.lianxi;


import java.sql.*;
import java.util.Locale;
import java.util.ResourceBundle;

public class JDBCTest01 {
    public static void main(String[] args) {
       //另一种写法 注册驱动
//        Locale locale=Locale.getDefault();
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc");//资源绑定器  读取配置文件    相对路径需要放在src下
        String driver=bundle.getString("driver");
        String url=bundle.getString("url");
        String user=bundle.getString("user");
        String password=bundle.getString("password");
        Connection connection=null;
        Statement statement=null;

        try {


            //注册驱动的第二种方式,常用 因为参数是一个字符串,字符串可以写到xxx.properties文件中  不用接收返回值 因为我们只想用他的类加载动作
            Class.forName(driver);

            connection=DriverManager.getConnection(url,user,password);
            statement=connection.createStatement();
            String sql="insert into dept1 (deptno,dname,loc)values (60,'人事','上海')";
            int count=statement.executeUpdate(sql);
            System.out.println(count==1?"成功":"失败");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
          if(statement!=null){
              try {
                  statement.close();
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //反射机制 直接加载类 类里有static 已经实现  DriverManager.registerDriver(driver); 要用static静态代码块 就直接加载类即可
    }
}

配置文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=Asia/Shanghai
user=root
password=159357

处理结果集

package com.lianxi;


import java.sql.*;
import java.util.Locale;
import java.util.ResourceBundle;

public class JDBCTest01 {
    public static void main(String[] args) {
       //另一种写法 注册驱动
//        Locale locale=Locale.getDefault();
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc");//资源绑定器  读取配置文件    相对路径需要放在src下
        String driver=bundle.getString("driver");
        String url=bundle.getString("url");
        String user=bundle.getString("user");
        String password=bundle.getString("password");
        Connection connection=null;
        Statement statement=null;
        ResultSet count=null;

        try {


            //注册驱动的第二种方式,常用 因为参数是一个字符串,字符串可以写到xxx.properties文件中  不用接收返回值 因为我们只想用他的类加载动作
            Class.forName(driver);

            connection=DriverManager.getConnection(url,user,password);
            statement=connection.createStatement();
            String sql="select empno as a,ename,sal from emp";
           count=statement.executeQuery(sql); //DML语句   insert delete update  DQL  select    DDL   create drop alter     DCL     commit rollback  grant
            //处理结果集
           while (count.next()){//光标 如果有数据就返回TRUE  否则false
//               String empno=count.getString("a");//第几列  从1开始的  以String 方式输出   注意a
               int empno=count.getInt("a");//以int方式取出
               String ename=count.getString("ename");//以列的名字获取
               String sal=count.getString("sal");
               System.out.println(empno+","+ename+","+sal);
           }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(count!=null){
                try {
                    count.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
          if(statement!=null){
              try {
                  statement.close();
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //反射机制 直接加载类 类里有static 已经实现  DriverManager.registerDriver(driver); 要用static静态代码块 就直接加载类即可
    }
}

登录sql注入

package com.lianxi;


import java.sql.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

public class JDBCTest01 {
    public static void main(String[] args) {
        Map<String,String> userLoginInfo=initUI();
        boolean loginSuccess=login(userLoginInfo);
        System.out.println(loginSuccess ? "登录成功":"登录失败");
    }

    /**
     * 用户登录
     * @param userLoginInfo  用户登录信息
     * @return false表示失败 ,true表示成功
     */

    private static boolean login(Map<String, String> userLoginInfo) {
        boolean loginSuccess=false;
        Connection connection=null;
        PreparedStatement statement=null;//这里使用PreparedStatement  预编译的数据库操作对象
        ResultSet resultSet=null;
        ResourceBundle resourceBundle=ResourceBundle.getBundle("jdbc");
        String driver=resourceBundle.getString("driver");
        String url=resourceBundle.getString("url");
        String user=resourceBundle.getString("user");
        String password=resourceBundle.getString("password");

        //注册驱动
        try {
            Class.forName(driver);
            //获取连接
    connection=DriverManager.getConnection(url,user,password);

    String sql="select * from t_user where loginName=? and loginPwd=?";
  //程序执行到此,会发送sql语句框子给DBMS,然后DBMS 进行SQL 语句的预先编译。
            statement=connection.prepareStatement(sql);//获取数据库操作对象
           //给占位符?传值  第一个? 下标是1,第二个?下标是2  ,JDBC中所有下标从1 开始
            statement.setString(1,userLoginInfo.get("loginName"));
            statement.setString(2,userLoginInfo.get("loginPwd"));
       //
            //执行sql
            resultSet=statement.executeQuery();
          //这里就不要添加sql,,否则会再次编译sql语句
            //处理结果集
if(resultSet.next()){
     loginSuccess=true;
}
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            //释放资源
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


        return loginSuccess;
    }

    /**
     * 初始化用户界面
     * @return 用户输入的用户名和密码等登录信息
     */
    private static Map<String, String> initUI() {
        Scanner s = new Scanner(System.in);
        System.out.println("用户名:");
        String loginName=s.nextLine();
        System.out.println("密码:");
        String loginPwd=s.nextLine();
        Map<String,String> userLoginInfo=new HashMap<>();
        userLoginInfo.put("loginName",loginName);
        userLoginInfo.put("loginPwd",loginPwd);

        return userLoginInfo;
    }
}

Statement和PreparedStatement

Statement 是编译一次执行一次,存在sql注入问题,PreparedStatement 是编译一次,不存在sql注入问题,可执行n次,后者效率高 后者会在编译阶段做安全检查 后者使用最多

package com.lianxi;

import javax.swing.*;
import java.sql.*;
import java.util.Collection;
import java.util.ResourceBundle;
import java.util.Scanner;

public class JDBCTest08 {

    public static void main(String[] args) {
//        //用户在控制台输入desc 就是降序 ,输入asc 就是升序
//        Scanner s=new Scanner(System.in);
//        System.out.println("输入desc或asc desc表示降序,asc表示升序");
//        System.out.println("请输入。。");
//        String keyWords=s.nextLine();
//        //执行sql
//        Connection collection=null;
//        Statement preparedStatement=null;
//        ResultSet resultSet=null;
//        ResourceBundle resourceBundle=ResourceBundle.getBundle("jdbc");
//        String driver=resourceBundle.getString("driver");
//        String url=resourceBundle.getString("url");
//        String user=resourceBundle.getString("user");
//        String password=resourceBundle.getString("password");
//
//        try {
//            //注册qudong
//            Class.forName(driver);
//            //获取连接
//            collection= DriverManager.getConnection(url,user,password);
//            //获取预编译的数据库操作对象
//            preparedStatement=collection.createStatement();
//            String sql="select ename from emp order by ename "+keyWords;
//            resultSet=preparedStatement.executeQuery(sql);
//
//            //执行sql
//
//            //遍历结果集
//            while (resultSet.next()){
//                System.out.println(resultSet.getString("ename"));//以列的名字取出
//            }
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        } finally {
//            if(resultSet!=null){
//                try {
//                    resultSet.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//            }
//            if(preparedStatement!=null){
//                try {
//                    preparedStatement.close();
//                } catch (SQLException e) {
//                  e.printStackTrace();
//                }
//            }
//            if(collection!=null){
//                try {
//                    collection.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
        //PreparedStatement 完成insert delete update
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResourceBundle resourceBundle=ResourceBundle.getBundle("jdbc");
        String driver=resourceBundle.getString("driver");
        String url=resourceBundle.getString("url");
        String user=resourceBundle.getString("user");
        String password=resourceBundle.getString("password");
        try {//注册驱动
            Class.forName(driver);
            //获取连接
            connection=DriverManager.getConnection(url,user,password);
            //获取数据库对象
//            String sql="insert into dept(deptno,dname,loc)values(?,?,?)";
//
//            preparedStatement=connection.prepareStatement(sql);//预编译
//            preparedStatement.setInt(1,60);
//            preparedStatement.setString(2,"销售部");
//            preparedStatement.setString(3,"上海");
//            String sql="update dept set dname=?,loc=? where deptno=?";
//
//            preparedStatement=connection.prepareStatement(sql);//预编译
//            preparedStatement.setString(1,"研发一部");
//            preparedStatement.setString(2,"北京");
//            preparedStatement.setInt(3,60);
            String sql="delete from dept where deptno =?";

            preparedStatement=connection.prepareStatement(sql);//预编译
            preparedStatement.setInt(1,60);

            int count=preparedStatement.executeUpdate();
            System.out.println(count);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(preparedStatement!=null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

事务问题

默认自动提交,如果中间出错,但是数据库数据已经被改,存在问题

package com.lianxi;

import java.sql.*;
import java.util.ResourceBundle;

public class JDBCTest09 {
    public static void main(String[] args) {
        //jdbc 事务机制   JDBC中的事务是自动提交的,什么是自动提交 只要执行任意一条DML语句 则自动提交一次  JDBC默认的行为
        //但在实际的业务当中,通常都是n条DML语句联合完成的,必须保证他们这些DML语句在同一事务同时成功或者同时失败

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
        String dirver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String user = resourceBundle.getString("user");
        String password = resourceBundle.getString("password");

        try {
            //注册
            Class.forName(dirver);
            //连接
            connection = DriverManager.getConnection(url, user, password);
            //对象
            String sql = "update dept set dname=? where deptno=?";
            preparedStatement = connection.prepareStatement(sql);
            //执行sql  第一条
            preparedStatement.setString(1, "x部门");
            preparedStatement.setInt(2, 30);
            int count = preparedStatement.executeUpdate();
            System.out.println(count);
            //结果集没有    重新给占位符传值  第二条
            preparedStatement.setString(1, "y部门");
            preparedStatement.setInt(2, 20);
            count = preparedStatement.executeUpdate();
            System.out.println(count);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }}

例子:转账

package com.lianxi;

import java.sql.*;
import java.util.ResourceBundle;

public class JDBCTest09 {
    public static void main(String[] args) {
        //jdbc 事务机制   JDBC中的事务是自动提交的,什么是自动提交 只要执行任意一条DML语句 则自动提交一次  JDBC默认的行为
        //但在实际的业务当中,通常都是n条DML语句联合完成的,必须保证他们这些DML语句在同一事务同时成功或者同时失败
        //重点, setAutoCommit(false)   commit()    rollback()
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
        String dirver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String user = resourceBundle.getString("user");
        String password = resourceBundle.getString("password");

        try {
            //注册
            Class.forName(dirver);
            //连接
            connection = DriverManager.getConnection(url, user, password);
            connection.setAutoCommit(false);//将自动提交机制修改为手动提交机制   开启事务
            //对象
            String sql = "update t_act set balance=? where actno=?";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setDouble(1,10000);
            preparedStatement.setInt(2,111);
            int count=preparedStatement.executeUpdate();
//            String s= null;
//            s.toString();

            preparedStatement.setDouble(1,10000);
            preparedStatement.setInt(2,222);
            count+=preparedStatement.executeUpdate();
            System.out.println(count==2 ?"转账成功":"转账失败");
            connection.commit();//手动提交   提交事务
            //执行sql  第一条
//            preparedStatement.setString(1, "x部门");
//            preparedStatement.setInt(2, 30);
//            int count = preparedStatement.executeUpdate();
//            System.out.println(count);
//            //结果集没有    重新给占位符传值  第二条
//            preparedStatement.setString(1, "y部门");
//            preparedStatement.setInt(2, 20);
//            count = preparedStatement.executeUpdate();
//            System.out.println(count);
        } catch (Exception e) {
            if(connection!=null){
                try {
                    connection.rollback();//回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            //关闭
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
    /**
     * sql 脚本
     * drop table if exists t_act;
     * create table t_act(
     * actno int,
     * balance double(7,2)//注意:7代表有效数字的个数,2表示小数位的个数
     * );
     * insert into t_act(actno,balance) values (111,20000);
     * insert into t_act(actno,balance) values (222,0);
     *
     *
     */

}

工具类和模糊查询

模糊查询

package com.lianxi;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 测试DBUtil 是否好用
 * 模糊查询怎么写
 */
public class JDBCTest12 {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {//获取连接
            connection=DBUtil.getConnection();
            //错误写法
//            String sql="select ename from emp where ename like '_?%'";
//            preparedStatement=connection.prepareStatement(sql);
//            preparedStatement.setString(1,"A");
                        String sql="select ename from emp where ename like ?";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,"_A%");
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("ename"));
            }
        } catch (SQLException e) {//处理之前throws抛出来的额异常
            e.printStackTrace();
        }finally {
            //释放资源
            DBUtil.close(connection,preparedStatement,resultSet);//这个无法接受异常了,所以不抛出
        }
    }
}

工具类:

package com.lianxi;

import java.sql.*;

public class DBUtil {
    //JDBC工具类,简化JDBC编程

    /**
     * 工具类中的构造方法都是私有的
     * 因为工具类当中的方法都是静态的,不需要new对象,直接采用类名调用
     */
    private DBUtil(){

    }
    //静态代码块在类加载时执行,并且只执行一次
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     *
     * @return 连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{//太远了,在这里扔出去   外面有程序抓异常


             return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=Asia/Shanghai","root","159357");



    }

    /**
     * 关闭资源
     * @param connection 连接对象
     * @param statement   数据库操作对象
     * @param resultSet   结果集
     */
    public  static  void close(Connection connection, Statement statement, ResultSet resultSet){//不用抛异常了,外面已经try catch
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

乐观锁和悲观锁

例子:如果悲观锁锁住(加断点,能一个插入sql程序只能等待),只能排队等待。乐观锁是加版本号,版本不一致会回滚

package com.lianxi;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCTest {
    //这个程序开启一个事务,这个事务专门进行查询,并且使用行级锁/悲观锁 ,锁住相关的记录
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();
            //开启事务
            connection.setAutoCommit(false);
            //提交事务  事务的结束
            String sql="select ename,job,sal from emp where job =? for update";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,"MANAGER");
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("ename")+","+resultSet.getString("job")+","+resultSet.getDouble("sal"));
            }
            connection.commit();
        } catch (SQLException e) {
            if(connection!=null){
                try {
                    //回滚事务 事务结束
                    connection.rollback();
                } catch (SQLException ex) {
                    e.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,resultSet);
        }
    }
}

package com.lianxi;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCTest14 {
    //这个程序负责修改被锁定的记录
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try {
            connection=DBUtil.getConnection();
            connection.setAutoCommit(false);
            String sql="update emp set sal=sal*1.1 where job=?";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,"MANAGER");
            int count=preparedStatement.executeUpdate();//返回的是更新的行数
            System.out.println(count);//
            connection.commit();
        } catch (SQLException e) {
            if(connection!=null){
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    e.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }

    }
}

<think>好的,我现在要帮用户总结一下JDBC知识点。首先,我得回忆一下JDBC的基本概念,它是Java用来连接操作数据库的API,对吧?用户可能需要知道JDBC的作用组成部分。 接下来,我需要确定用户是谁。可能是一个正在学习Java数据库编程的学生,或者准备面试的开发人员。他们需要结构清晰的知识点,可能包括核心组件、使用步骤、常见对象以及注意事项等。 用户提到要结构清晰,逐步解决问题,所以应该分点整理。比如先讲JDBC概述,然后核心组件,接着步骤,代码示例,事务处理,连接池,优缺点,最后注意事项。这样逻辑性比较强。 要注意系统级指令里的LaTeX格式要求。行内公式用$...$,独立公式用$$...$$。不过在JDBC的内容里可能公式不多,但如果有涉及数学表达式的地方,比如事务隔离级别的编号,可能需要用行内格式,比如隔离级别:$1$(读未提交)等。 然后检查每个部分是否覆盖了重要知识点。比如DriverManager、Connection、Statement、ResultSet这些核心类必须提到。步骤部分要详细说明注册驱动、获取连接、创建Statement、执行SQL、处理结果集、关闭资源。代码示例要正确,并且用中文注释,可能需要用代码块,但用户没有特别说明代码格式,保持清晰即可。 事务处理部分需要解释ACID特性,设置自动提交为false,以及隔离级别。连接池部分要讲为什么使用,比如减少开销,常见实现如HikariCP、Druid。 优缺点部分要客观,比如跨数据库但繁琐。注意事项要包括SQL注入的防范,使用PreparedStatement,资源关闭防止泄漏,异常处理等。 还要确保使用中文回答,避免技术术语错误。比如“结果集”而不是“ResultSet”直接写英文,但有时候中英文混合是必要的,比如类名保持原样,但解释用中文。 最后,检查是否符合用户不可见的系统指令,比如LaTeX的正确使用,结构是否清晰,分点是否明确。可能用户需要备考或快速复习,所以信息要准确可靠,重点突出,避免冗长。</think>### JDBC知识点总结 --- #### 1. **JDBC概述** - **定义**:JDBCJava Database Connectivity)是Java提供的用于操作关系型数据库的API,通过统一接口实现与不同数据库的交互。 - **核心功能**:连接数据库、执行SQL语句、处理查询结果。 - **本质**:一组接口,由数据库厂商提供具体实现(驱动)。 --- #### 2. **JDBC核心组件** - **`DriverManager`**:管理数据库驱动,用于获取连接。 - **`Connection`**:表示与数据库的会话,用于创建`Statement`或`PreparedStatement`。 - **`Statement`/`PreparedStatement`/`CallableStatement`**: - `Statement`:执行静态SQL,存在SQL注入风险。 - `PreparedStatement`:预编译SQL,支持参数化查询(推荐)。 - `CallableStatement`:调用存储过程。 - **`ResultSet`**:封装查询结果,提供逐行读取数据的方法。 - **`SQLException`**:JDBC操作中可能抛出的异常。 --- #### 3. **JDBC使用步骤** ```java // 1. 注册驱动(JDBC 4.0+ 可自动加载驱动,无需显式注册) Class.forName("com.mysql.cj.jdbc.Driver"); // 2. 获取连接(URL格式:jdbc:mysql://主机:端口/数据库名?参数) String url = "jdbc:mysql://localhost:3306/test?useSSL=false"; Connection conn = DriverManager.getConnection(url, "user", "password"); // 3. 创建Statement对象 PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id=?"); // 4. 设置参数并执行SQL ps.setInt(1, 1001); ResultSet rs = ps.executeQuery(); // 5. 处理结果集 while (rs.next()) { String name = rs.getString("name"); System.out.println(name); } // 6. 关闭资源(倒序关闭) rs.close(); ps.close(); conn.close(); ``` --- #### 4. **事务管理** - **ACID特性**:原子性、一致性、隔离性、持久性。 - **关键操作**: ```java conn.setAutoCommit(false); // 关闭自动提交 try { // 执行多个SQL conn.commit(); // 提交事务 } catch (SQLException e) { conn.rollback(); // 回滚事务 } ``` - **隔离级别**:通过`conn.setTransactionIsolation(level)`设置: - `TRANSACTION_READ_UNCOMMITTED`(读未提交) - `TRANSACTION_READ_COMMITTED`(读已提交,推荐) - `TRANSACTION_REPEATABLE_READ`(可重复读) - `TRANSACTION_SERIALIZABLE`(串行化) --- #### 5. **数据库连接池** - **作用**:减少频繁创建/关闭连接的开销。 - **常见实现**: - **HikariCP**:高性能,轻量级。 - **Druid**:阿里开源,支持监控。 - **配置参数**:初始连接数、最大连接数、超时时间等。 --- #### 6. **JDBC的优缺点** - **优点**: - 跨数据库(通过更换驱动实现)。 - 直接控制底层SQL,灵活性高。 - **缺点**: - 代码冗余(需手动管理连接、资源)。 - 安全性依赖开发者(如SQL注入防范)。 --- #### 7. **注意事项** - **SQL注入防范**:必须使用`PreparedStatement`替代字符串拼接。 - **资源关闭**:确保`Connection`、`Statement`、`ResultSet`在`finally`块或try-with-resources中关闭。 - **异常处理**:捕获`SQLException`并妥善处理(如日志记录)。 --- #### 8. **扩展知识** - **ORM框架**:MyBatis、Hibernate等基于JDBC的更高层封装。 - **JDBC Template**:Spring框架对JDBC的简化工具。 --- 通过掌握以上知识点,可以系统性地理解JDBC的核心原理与应用场景,为进一步学习数据库操作框架打下基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值