jdbc知识点和代码块

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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);
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值