快速学习JDBC




1. JDBC本质理解

在这里插入图片描述

在这里插入图片描述



2.模拟JDBC

在这里插入图片描述

通过反射机制进行优化:

JDBC是父亲(接口)
在这里插入图片描述



通过配置文件继续优化

通过如下方法在这里插入图片描述
获取配置文件中的数据库名字。

之后可以直接改配置文件就行
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述



3.JDBC编程六步操作【重点】

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述



3.1 JDBC执行增删改

在这里插入图片描述
在这里插入图片描述



3.2 注册驱动的常用方式

在这里插入图片描述



3.3 使用ResourceBundle读取配置文件

在这里插入图片描述



3.4 JDBC执行 查

遍历结果集过程:
在这里插入图片描述
弱智版代码:
在这里插入图片描述
升级版代码:
在这里插入图片描述
在这里插入图片描述




4.IDEA JDBC

4.1 配置jdbc环境

在这里插入图片描述
在这里插入图片描述




4.2 使用Statement(存在sql注入问题)

/*
实现功能:
    1.需求:模拟用户登录功能的实现
    2.业务描述:
        程序运行的时候,提供一个输入的入口,可以让用户输入用户名和密码
        用户输入用户名和密码之后,提交信息,java程序收集到用户信息
        Java程序连接数据库验证用户名和密码是否合法
        合法:显示登录成功
        不合法:显示登陆失败
    3.数据的准备:
        在实际开发中,表的设计会使用专业的建模工具,我们这里安装一个建模工具:PowerDesigner
        使用PD工具来进行数据库表的设计。(参见user-login.sql脚本)
    4.当前程序存在的问题:
        用户名:fdsa
        密码:fdsa' or '1'='1
        登陆成功
        这种现象被称为SQL注入。(黑客经常使用)
    5.导致SQL注入的根本原因是什么?
        用户输入的信息中含有sql语句的关键字,并且这些关键字参与sql语句的编译过程。
        导致sql语句的愿意被扭曲,进而达到sql注入。
 */
public class JDBCTest06 {
    public static void main(String[] args) {

        //初始化一个界面
        Map<String,String> userLoginInfo = initUI();
        //验证用户名和密码
        boolean loginSuccess = login(userLoginInfo);
        //最后输出结果
        System.out.println(loginSuccess ? "登录成功" : "登陆失败");
    }

    /**
    * @Description :
    * @Param : [userLoginInfo] 用户登录信息
    * @author : Yemulin
    * @date : 2020/8/25 18:20
    * @return : boolean false表示失败,true表示成功
    * @throws :
    */
    private static boolean login(Map<String, String> userLoginInfo) {

        //打标记的意识
        boolean loginSuccess = false;
        //单独定义变量
        String loginName = userLoginInfo.get("loginName");
        String loginPwd = userLoginInfo.get("loginPwd");

        //JDBC代码
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?useSSL=false", "root", "000");
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            //4.执行sql
            String sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'";
            //以上正好完成了sql语句的拼接,以下代码的含义是,发送sql语句给DBMS,DBMS进行sql编译
            //正好将用户提供的“非法信息”编译进去。导致了原sql语句的含义被扭曲了、
            rs = stmt.executeQuery(sql);
            //5.处理结果集
            if (rs.next()) {
                //登陆成功
                loginSuccess = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return loginSuccess;
    }

    /**
    * @Description : 初始化用户界面
    * @Param : []
    * @author : Yemulin
    * @date : 2020/8/25 18:03
    * @return : java.util.Map<java.lang.String,java.lang.String>用户输入的用户名和密码等登录信息
    * @throws :
    */
    private static Map<String, String> initUI() {

        Scanner s = new Scanner(System.in);

        System.out.println("用户名:");
        String username = s.nextLine();

        System.out.println("密码:");
        String password = s.nextLine();

        Map<String, String> userLoginInfo = new HashMap<>();
        userLoginInfo.put("loginName", username);
        userLoginInfo.put("loginPwd", password);

        return userLoginInfo;

    }
}



4.3 使用PreparedStatement进行升级

解决了sql注入问题

/**
 * 1.解决Sql注入问题?
 * 		只要用户提供的信息不参与sql语句的编译过程,问题就解决了
 * 		即使用户提供的信息中含有sql语句的关键字,但是没有参与编译,不起作用
 * 		要想用户信息不参与sql语句的编译,那么必须使用java.sql.PreparedStatement
 * 		PrepareedStatement接口继承了java.sql.Statement
 * 		PrepareedStatement是属于预编译的数据库操作对象
 * 		PrepareedStatement的原理是:	预先对sql语句的框架进行编译,然后再给sql语句传“值”。
 *
 * 2、对比一下Statement和PreparedStatement?
 * 	-	Statement存在sql注入问题,PreparedStatement解决了sql注入问题
 * 	-	Statement是编译一次执行一次。PreparedStatement是编译一次执行n次,效率更高
 * 	-	PreparedStatement会在编译阶段做类型的安全检查。
 *
 * 		综上:PreparedStatement使用较多。只有极少数使用Statement
 *
 * 3.什么情况下必须使用Statement呢?
 * 	凡是业务方面要求是需要进行sql语句拼接的,必须用Statement
 */
public class JDBCTest07 {
	public static void main(String[] args) {

		//初始化一个界面
		Map<String,String> userLoginInfo = initUI();
		//验证用户名和密码
		boolean loginSuccess = login(userLoginInfo);
		//最后输出结果
		System.out.println(loginSuccess ? "登录成功" : "登陆失败");
	}

	/**
	 * @Description :
	 * @Param : [userLoginInfo] 用户登录信息
	 * @author : Yemulin
	 * @date : 2020/8/25 18:20
	 * @return : boolean false表示失败,true表示成功
	 * @throws :
	 */
	private static boolean login(Map<String, String> userLoginInfo) {

		//打标记的意识
		boolean loginSuccess = false;
		//单独定义变量
		String loginName = userLoginInfo.get("loginName");
		String loginPwd = userLoginInfo.get("loginPwd");

		//JDBC代码
		Connection conn = null;
		PreparedStatement ps = null; //这里使用PreparedStatement
		ResultSet rs = null;

		try {
			//1.注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			//2.获取连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?useSSL=false", "root", "000");
			//3.获取预编译的数据库操作对象
			//sql语句的框子。其中一个?表示一个占位符。一个?将来接收一个“值”,注意:占位符不能用单引号括起来
			String sql = "select * from t_user where loginName = ? and loginPwd = ? ";
			//程序执行到此处,会发送sql语句框子给DBMS,然后DBMS进行sql语句的预先编译
			ps = conn.prepareStatement(sql);
			//给占位符?传值(第一个问号下标是1,第二个问号下标是2,JDBC中所有下标从1开始)
			ps.setString(1, loginName);
			ps.setString(2, loginPwd);
			//4.执行sql
			rs = ps.executeQuery();
			//5.处理结果集
			if (rs.next()) {
				//登陆成功
				loginSuccess = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//6.释放资源
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		return loginSuccess;
	}

	/**
	 * @Description : 初始化用户界面
	 * @Param : []
	 * @author : Yemulin
	 * @date : 2020/8/25 18:03
	 * @return : java.util.Map<java.lang.String,java.lang.String>用户输入的用户名和密码等登录信息
	 * @throws :
	 */
	private static Map<String, String> initUI() {

		Scanner s = new Scanner(System.in);

		System.out.println("用户名:");
		String username = s.nextLine();

		System.out.println("密码:");
		String password = s.nextLine();

		Map<String, String> userLoginInfo = new HashMap<>();
		userLoginInfo.put("loginName", username);
		userLoginInfo.put("loginPwd", password);

		return userLoginInfo;

	}
}



4.4 必须使用Statement的情况(必须要求用户进行sql注入)

进行了两种接口的对比

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.print("请输入:");
        String keyWords = s.nextLine();

        //执行sql
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?useSSL=false", "root", "000");
            //获取预编译的数据库操作对象
            String sql = "select ename from emp order by ename ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, keyWords);
            //执行sql
            rs = ps.executeQuery();
            //遍历结果集
            while (rs.next()) {
                rs.getString("ename");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

         */

        //用户在控制台输入desc就是降序,输入asc就是升序
        Scanner s = new Scanner(System.in);
        System.out.println("请输入desc或者asc,desc表示降序,asc表示升序");
        System.out.print("请输入:");
        String keyWords = s.nextLine();

        //执行sql
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?useSSL=false", "root", "000");
            //获取数据库操作对象
            stmt = conn.createStatement();
            //执行sql
            String sql = "select ename from emp order by ename " + keyWords;
            rs = stmt.executeQuery(sql);
            //遍历结果集
            while (rs.next()) {
                System.out.println(rs.getString("ename"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



4.5 JDBC事务的控制【重点】

  • 重点三行代码?:
  •  conn.setAutoCommit(false); //开启事务,设置为手动提交
    
  •  conn.commit(); //提交事务(标志着事务的结束)
    
  •  conn.rollback(); //回滚事务(如果conn!=null,意味着提交失败,所以需要回滚。所以放在catch{}里)(同样标志着事务的结束)
    
/**
 *
 * 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);
 * commit;
 * select * from t_act;
 *
 * 重点三行代码?
 *      conn.setAutoCommit(false);
 *      conn.commit();
 *      conn.rollback();
 *
 * @ClassName : JDBCTest11  
 * @Description :   
 * @Author : Yemulin  
 * @Date : 2020/08/26 03:22  
 * @Version : 1.0
 */

public class JDBCTest11 {
    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement ps = null;


        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?useSSL=false","root","000");

            //讲自动提交机制修改为手动提交
            conn.setAutoCommit(false); //开启事务
            String sql = "update t_act set balance = ? where actno = ?";
            ps = conn.prepareStatement(sql);
            ps.setDouble(1,10000);
            ps.setInt(2,111);
            int count = ps.executeUpdate();

            //制造空指针异常,检查系统是不是会丢10000块钱
            String s = null;
            s.toString();

            ps.setDouble(1,10000);
            ps.setInt(2,222);
            count += ps.executeUpdate();

            System.out.println(count ==2 ? "转账成功" : "转账失败");

            //程序能够走到这里说明以上程序没有异常,事务结束,手动提交数据
            conn.commit(); //提交事务

        } catch (Exception e) {
            //回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



4.6 JDBC工具类,简化JDBC编程

/**
 *
 * JDBC工具类,简化JDBC编程。
 *
 * @ClassName : DBUtils  
 * @Description :   
 * @Author : Yemulin  
 * @Date : 2020/08/26 15:37  
 * @Version : 1.0
 */

public class DBUtils {

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

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

        }

/**
* @Description : 获取数据库连接对象
* @Param : []
* @author : Yemulin
* @date : 2020/8/26 16:01
* @return : java.sql.Connection 连接对象
* @throws : SQLException
*/

    public static Connection  getConnection() throws SQLException {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?useSSL=false", "root", "0000");
    }

/**
 * @Description :
 * @author : Yemulin
 * @date : 2020/8/26 16:53 
 * @param conn : 连接对象
 * @param stmt : 数据库操作对象
 * @param rs : 结果集
 * @return : void
 * @throws : 
 */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}



4.7 JDBC工具类使用演示

/**
 * @ClassName : JDBCTest12  
 * @Description :  这个程序两个任务:
 *                    第一:测试DBUtils是否好用
 *                    第二:模糊查询怎么写?
 * @Author : Yemulin  
 * @Date : 2020/08/26 16:58  
 * @Version : 1.0
 */

public class JDBCTest12 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            //获取连接
            conn = DBUtils.getConnection();
            //获取预编译的数据库对象
            String sql = "select ename from emp where ename like ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "_A%");
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString("ename"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            DBUtils.close(conn,ps,rs);
        }
    }

}



4.8 悲观锁与乐观锁

在这里插入图片描述



4.9 悲观锁update演示

演示方法:1.给代码1中的conn.commit();语句增加断点,debug至断点。
2.运行代码2。此时控制台无输出。
3。代码1debug至结束。此时代码2的控制台输出3。

/**
 * @ClassName : JDBCTest13  
 * @Description :  这个程序开启一个事务,这个事务专门进行查询,并且使用行级锁/悲观锁,
 *                  锁住相关的记录。
 * @Author : Yemulin  
 * @Date : 2020/08/26 17:51  
 * @Version : 1.0
 */

public class JDBCTest13 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);

            String sql = "select ename,job,sal from emp where job = ? for update ";
            ps = conn.prepareStatement(sql);
            ps.setString(1,"MANAGER");
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString("ename") + "," + rs.getString("job") + ","
                        + rs.getDouble("sal" ));
            }
            //提交事务(标志事务的结束)
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    //回滚事务(事务的结束)
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            DBUtils.close(conn,ps,rs);
        }
    }
}
/**
 * @ClassName : JDBCTest14  
 * @Description :  这个程序负责修改被锁定的记录
 * @Author : Yemulin  
 * @Date : 2020/08/26 17:51  
 * @Version : 1.0
 */

public class JDBCTest14 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtils.getConnection();
            conn.setAutoCommit(false);
            String sql = "update emp set sal = sal * 1.1 where job = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "MANAGER");
            int count = ps.executeUpdate();
            System.out.println(count);

            conn.commit();
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            DBUtils.close(conn,ps,null);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值