1.JDBC是什么?

Java DataBase Connectivity(Java语言连接数据库

2.JDBC的本质是什么?

JDBC是SUN公司制定的一套接口(interface)
java.sql.*;(这个软件包下有很多接口)

接口都有调用者和实现者。
面向接口调用、面向接口写实现类,这都属于面向接口编程。

为什么要面向接口编程?
解耦合:降低程序的耦合度,提高程序的扩展力。
		多态机制就是非常典型的:面向抽象编程。(不要面向具体编程)
			建议:
				Animal a = new Cat();
				Animal a = new Dog();
				// 喂养的方法
				public void feed(Animal a){ // 面向父类型编程。
				
			}
		不建议:
			Dog d = new Dog();
			Cat c = new Cat();
思考:为什么SUN制定一套JDBC接口呢?

因为每一个数据库的底层实现原理都不一样。

Oracle数据库有自己的原理。
MySQL数据库也有自己的原理。
MS SqlServer数据库也有自己的原理。

每一个数据库产品都有自己独特的实现原理。

JDBC的本质

一套接口。
在这里插入图片描述

编写程序模拟JDBC的本质

/*
SUN公司负责制定这套JDBC接口。
*/

public interface JDBC
{
	/*
	连接数据库的方法。
	*/

	void getConnection();
}

/*
MySQL的数据库厂家负责编写JDBC接口的实现类
*/

public class MySQL implements JDBC{

	public void getConnection(){
		//具体这里的代码怎么写,对于我们Java程序员来说没关系。
		//这段代码涉及到MySQL底层数据库的实现原理。
		System.out.println("连接MySQL数据库成功!");
	
	} 

}


//实现类被称为驱动。(MySQL驱动)
/*
Oracle的数据库厂家负责编写JDBC接口的实现类
*/

public class Oracle implements JDBC{

	public void getConnection(){
		//具体这里的代码怎么写,对于我们Java程序员来说没关系。
		//这段代码涉及到Oracle底层数据库的实现原理。
		System.out.println("连接Oracle数据库成功!");
	
	} 

}


//实现类被称为驱动。(Oracle驱动)
/*
SqlServer的数据库厂家负责编写JDBC接口的实现类
*/

public class SqlServer implements JDBC{

	public void getConnection(){
		//具体这里的代码怎么写,对于我们Java程序员来说没关系。
		//这段代码涉及到SqlServer底层数据库的实现原理。
		System.out.println("连接SqlServer数据库成功!");
	
	} 

}


//实现类被称为驱动。(SqlServer驱动)

//xxx.jar 当中有很多.class都是对JDBC接口进行的实现。

/*
	Java程序员角色
	不需要关心具体是哪个品牌的数据库,只需要面向JDBC 接口写代码。
	面向接口编程、面向抽象编程,不要面向具体编程。
*/

public class JavaProgrammer
{

	public static void main(String[] args) throws Exception{
		//JDBC jdbc = new MySQL();
		//JDBC jdbc = new Oracle();
		//JDBC jdbc = new SqlServer();

		//创建对象可以通过反射机制。
		//Class c = Class.forName("MySQL");
		//Class c = Class.forName("Oracle");
		//Class c = Class.forName("SqlServer");

       //通过配置文件获取
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
		String className = bundle.getString("className");
		Class c = Class.forName(className);
		JDBC jdbc = (JDBC)c.newInstance();
		JDBC jdbc = (JDBC)c.newInstance();
		//以下代码都是面向接口调用方法,不需要修改
		jdbc.getConnection();
	
	}
}

jdbc.properties

className=Oracle

直接在当前目录的地址栏下输入cmd,然后回车进入Dos窗口
在这里插入图片描述
javac *.java 编译
java Javaprogrammer 运行
在这里插入图片描述

3.JDBC开发前的准备工作,先从官网上下载对应的驱动jar包,然后将其配置到环境变量classpath当中

在这里插入图片描述
在这里插入图片描述
查看环境变量中是否有classpath变量,如果上下都没有,新建如下:

输入变量名:classpath
变量值:.;D:\course\06-JDBC\resources\MySql Connector Java 5.1.23\mysql-connector-java-5.1.23-bin.jar
【注意】:.; 千万不可以省略。

 .  代表当前路径,如果删掉这个点代表当前路径写死了,以后自己写的Java程序也没法运行了,因为会自动全到mysql-connector-java-5.1.23-bin.jar中找。
 ; 必须是英文的分号

在这里插入图片描述

以上的配置是针对于文本编辑器的方式开发,使用IDEA工具的时候,不需要配置以上的环境变量。
IDEA有自己的配置方式。

4.JDBC编程六步(需要背会)

  • 第一步:注册驱动(作用:告诉Java程序,即将要连接的是哪个品牌的数据库
  • 第二步:获取连接(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,重量级的,使用完之后一定要关闭通道。)
  • 第三步:获取数据库操作对象(专门执行sql语句的对象)
  • 第四步:执行SQL语句(DQL DML…)
  • 第五步:处理查询结果集(只有当第四步执行的是select语句的时候,才有这第五步处理查询结果集。)
  • 第六步:释放资源(使用完资源之后一定要关闭资源。Java和数据库属于进程之间的通信,开启之后一定要关闭。)
JDBC 编程六步
/*
	JDBC 编程六步
*/
import java.sql.*;

public class JDBCTest01 {
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try{
			// 1、注册驱动
			Driver driver = new com.mysql.jdbc.Driver();//多态,父类型引用指向子类型对象
			//Driver driver = new com.oracle.jdbc.OracleDriver(); //Oracle的驱动
			
			DriverManager.registerDriver(driver);
			
			// 2、获取连接
			/*
			    url:统一资源定位符(网络中某个资源的绝对路径)
				https:www.baidu.com/  这就是一个URL
				url包括哪几部分:
					协议
					IP
					Port
					资源名

					eg:baidu
					http://182.61.200.7:80/index.html
					http://通信协议
					182.61.200.7 服务器IP地址
					80 服务器上软件的端口
					index.html 是服务器上某个资源名

					jdbc:mysql://127.0.0.1:3306/bjpowernode
					jdbc:mysql:// 协议
					127.0.0.1 IP地址
					3306 mysql数据库端口号
					bjpowernode 具体的数据库实例名

					说明:localhost和127.0.0.1都是本机IP地址。

					什么是通信协议,有什么用?
					通信协议是通信之前就提前定好的数据传送格式。
					数据包具体怎么传数据,格式提前定好的。


			*/
			// static Connection getConnection(String url, String user, String password)
			String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
			String user = "root";
			String password = "333";
			conn = DriverManager.getConnection(url,user,password);
			System.out.println("数据库连接对象" + conn);	//数据库连接对象com.mysql.jdbc.JDBC4Connection@1ae369b7

			// 3、获取数据库操作对象(Statement专门执行sql语句的)
			// Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库
                stmt = conn.createStatement();

			// 4、执行sql语句
			// int executeUpdate(String sql) 
			String sql = "insert into dept(deptno,dname,loc) values(50,'人事部','北京')";
			//专门执行DML语句的(insert delete update)
			// 返回值是“影响数据库中的记录条数”
			int connt = stmt.executeUpdate(sql); 
			//合并语句
			//int count = stmt.executeUpdate("update dept set dname = '销售部',loc = '合肥' where deptno = 20;");
			System.out.println(count == 1 ? "保存成功":"保存失败");

			// 5、处理查询结果集

		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			// 6、释放资源
			//为了保障资源一定释放,在finally语句块中关闭资源
			// 并且要遵循从小到大依次关闭
			//分别对其try..catah
			if(stmt != null) {
				try	{
					stmt.close();	
				}
				catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try	{
					conn.close();	
				}
				catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
JDBC完成Delete update
/*
	JDBC完成Delete update
*/
import java.sql.*;

public class JDBCTest02 {
	public static void main(String[] args) {
		
		Connection conn = null;
		Statement stmt = null;
		try {
			// 1、注册驱动
			Driver driver = new com.mysql.jdbc.Driver();
			DriverManager.registerDriver(driver);

			// 2、获取连接
			String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
			String user = "root";
			String password = "333";
			conn = DriverManager.getConnection(url,user,password);

			// 3、获取数据库操作对象
			stmt = conn.createStatement();
			// 4、执行sql语句
			//String sql = "delete from dept where deptno = 40";
			//JDBC中的SQL语句不需要提供分号结尾。
			String sql = "update dept set dname = '销售部',loc = '天津' where deptno = 20";
			int connt = stmt.executeUpdate(sql); 

			//合并语句
			//int count = stmt.executeUpdate("delete from dept where deptno = 50");

			System.out.println(count == 1? "删除成功":"删除失败");

			// 5、获取查询结果集

		} catch(SQLException e){
			e.printStackTrace();
		} finally {
			// 6、释放资源

			if(conn != null) {
				try {
					conn.close();
				} catch(SQLException e){
					e.printStackTrace();
				}
			}
			if(stmt != null) {
				try {
					stmt.close();
				} catch(SQLException e){
					e.printStackTrace();
				}
			}
		}
	}
}
注册驱动的另一种方式(这种方式常用)
/*
	注册驱动的另一种方式(这种方式常用)
*/

import java.sql.*;

public class JDBCTest03 {
	public static void main(String[] args) {
		try{
		    // 注册驱动
			//这是注册驱动的第一种写法
			//DriverManager.registerDriver(new com.mysql.jdbc.Driver());

			//注册驱动的第二种方式;常用的。(反射机制)
			//为什么这种方式常用?因为参数是一个字符串,字符串可以写到xxx.properties文件中。
			//以下方法不需要接收返回值,因为我们只想用它的类加载动作。
			Class.forName("com.mysql.jdbc.Driver");

			// 获取连接
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
			System.out.println(conn);

		} catch(SQLException e){
			e.printStackTrace();
		} catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
}
将连接数据库的所有信息配置到配置文件中

//将连接数据库的所有信息配置到配置文件中
/*
实际开放中不建议把连接数据库的信息写死到java程序中。
*/
import java.sql.*;
import java.util.*;

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

		//使用资源绑定器绑定属性配置文件
		ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
		String driver = bundle.getString("driver");
		String url = bundle.getString("url");
		String user = bundle.getString("user");
		String password = bundle.getString("password");
		
		Connection conn = null;
		Statement stmt = null;
		try {
			// 1、注册驱动
			Class.forName(driver);

			// 2、获取连接
			conn = DriverManager.getConnection(url,user,password);

			// 3、获取数据库操作对象
			stmt = conn.createStatement();
			// 4、执行sql语句
			String sql = "update dept set dname = '销售部2',loc = '天津2' where deptno = 20";
			int connt = stmt.executeUpdate(sql); 
			System.out.println(count == 1? "修改成功":"修改失败");

			// 5、获取查询结果集

		} catch(Exception e){
			e.printStackTrace();
		} finally {
			// 6、释放资源

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

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
user=root
password=333
处理查询结果集
/*
	处理查询结果集
*/
import java.sql.*;
import java.util.*;

public class JDBCTest005 {
	public static void main(String[] args) {
		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/bjpowernode","root","333");
			// 3、获取数据库操作对象
			stmt = conn.createStatement();
			// 4、执行sql语句
			String sql = "select empno,ename,sal from emp"// int executeUpdate(insert/delete/update)
			// ResultSet executeQuery(select)
			rs = stmt.executeQuery(sql);//专门执行DQL语句的方法。
			// 5、获取查询结果集
			while(rs.next()){
				/*
				//true
				//光标指向的行有数据
				//取数据
				//getString()方法的特点是:不管数据库中的数据类型是什么,都以String的形式取出。
				//以下程序的1,2,3说的是第几列
				String empno = rs.getString(1);//JDBC中所有下标从1开始。不是从0开始。
				String ename = rs.getString(2);
				String sal = rs.getString(3);
				System.out.println(empno + "," + ename + "," + sal);
				*/
				
				/*
				// 按下标取出,程序不健壮,以下是以列的名字获取
				String empno = rs.getString("empno");//重点注意:列名称不是表中的名称,是查询结果集的列名称
				String ename = rs.getString("ename");
				String sal = rs.getString("sal");
				System.out.println(empno + "," + ename + "," + sal);
				*/
				
				/*
				// 除了可以以String类型取出之外,还可以指定的类型取出
				int empno = rs.getInt(1);
				String ename = rs.getString(2);
				double sal = rs.getDouble(3);
				System.out.println(empno + "," + ename + "," + (sal + 100));
				*/

				int empno = rs.getInt("empno");
				String ename = rs.getString("ename");
				double sal = rs.getDouble("sal");
				System.out.println(empno + "," + ename + "," + (sal + 200));
			}

		} catch(Exception e){
			e.printStackTrace();
		}finally{
			// 6、释放资源
			if(rs != null){
				try{
					rs.close();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
			if(stmt != null){
				try{
					stmt.close();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
			if(conn != null){
				try{
					conn.close();
				} catch (Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}

遍历结果集
在这里插入图片描述

5.使用IDEA开发JDBC代码配置驱动

第一步:选中项目模块,单击右键选择如下菜单选项
在这里插入图片描述
第二步:选择库
在这里插入图片描述
第三步:选择java库
在这里插入图片描述
第四步:选择mysql驱动
在这里插入图片描述
第五步:选择导入到哪个模块
在这里插入图片描述
第六步:应用
在这里插入图片描述
引入成功
在这里插入图片描述

6.用户登录业务介绍

数据的准备

  • 在实际开发中,表的设计会使用专业的建模工具,我们这里安装一个建模工具,powerDesigner
  • 使用PD工具来进行数据表的设计

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
再次双击表格,进入设置,保存SQL脚本

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

在这里插入图片描述
数据没问题,使用工具可以正常显示
在这里插入图片描述

用户登录方法的实现
import java.sql.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;

/*
*
* 实现功能
*   1.需求:模拟实现用户登录功能
*   2.业务功能:
*       程序运行的时候,提供一个输入的入口,可以让用户输入用户名和密码
*       用户输入用户名和密码之后,提交信息,java程序收集到用户信息
*       java程序连接数据库验证用户名和密码是否合法
*       合法:显示登录成功
*       不合法:显示登录失败
*   3.数据的准备
*       在实际开发中,表的设计会使用专业的建模工具,我们这里安装一个建模工具,powerDesigner
*       使用PD工具来进行数据表的设计
*
*   4.当前程序出现的问题
*       用户名:fdsa
*       密码:fdsa ' or '1'='1
*       登录成功
*       这种现象被称为SQL注入(安全隐患),(黑客经常使用)
*   5。导致SQL注入的最根本原因是什么?
*
* */
public class JDBCTest06 {
    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;
        //单独定义变量
        String loginName = userLoginInfo.get("loginName");
        String loginPwd = userLoginInfo.get("loginPwd");

        //JDBC代码
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //3.获取数据库操作对象
            statement = connection.createStatement();
            //4.执行SQL
            String  sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'";
            //String sql = "select * from t_user where loginName = '"+userLoginInfo.get("loginName")+"' and  loginPwd = '"+userLoginInfo.get("loginPwd")+"'";
            resultSet = statement.executeQuery(sql);
            //5.处理结果集
            if (resultSet.next()){
                //登录成功
                loginSuccess = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            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();
                }
            }

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

【注意】:以下写法会报错。

 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","user");

我用的是8.0.21,在新版的数据库使用的时区与本地时区有区别,标准时区使用的是Unix元年的时间为起始点到当前时间中间所做的动作。国际标准失去与本地相差 8 个小时。

解决方法:

数据库名后面加 ?serverTimezone=UTC

UTC必须大写

 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
演示SQL注入现象

当前程序出现的问题

  • 用户名:fdsa
  • 密码:fdsa ’ or ‘1’='1
  • 登录成功
  • 这种现象被称为SQL注入(安全隐患),(黑客经常使用)
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
String  sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'";
 //以上正好完成了SQL语句的拼接,以下代码的含义是,发送SQL语句给DBMS,DBMS进行SQL编译
 //正好将用户提供的“非法信息”编译进去,导致原SQL语句的含义被扭曲了。
            
resultSet = statement.executeQuery(sql);
导致SQL注入的最根本原因是什么?
  • 用户输入的信息中含有SQL语句的关键字,并且这些关键字参与SQL语句的编译过程【参与编译了这是最关键的原因】。
  • 导致SQL语句的原意被扭曲了,进而达到SQL注入。
解决SQL注入问题
  • 只要用户提供的信息不参与SQL语句的编译过程,问题就解决了
  • 即使用户提供的信息中含有SQL语句的关键字,但是没有参与编译,不起作用
  • 要想用户信息不参与SQL语句的编译,那么必须使用java.sql.preparedStatement
  • PreparedStatement接口继承了java.sql.Statement
  • PreparedStatement是属于预编译的数据库操作对象。
  • PreparedStatement的原理 是,预先对SQL语句的框架进行编译,然后再给SQL语句传“值”。
解决SQL注入的关键是什么?

用户提供的信息中即使含有SQL语句的关键字,但是这些关键字并没有参与编译,不起作用。

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

/**
 * 1.解决SQL注入问题?
 *      只要用户提供的信息不参与SQL语句的编译过程,问题就解决了
 *      即使用户提供的信息中含有SQL语句的关键字,但是没有参与编译,不起作用
 *      要想用户信息不参与SQL语句的编译,那么必须使用java.sql.preparedStatement
 *      PreparedStatement接口继承了java.sql.Statement
 *      PreparedStatement是属于预编译的数据库操作对象。
 *      PreparedStatement的原理 是,预先对SQL语句的框架进行编译,然后再给SQL语句传“值”。
 *2.测试结果
 *      用户名:fdas
 *      密码:fdas' or '1'='1
 *      登录失败
 *3.解决SQL注入的关键是什么?
 *      用户提供的信息中即使含有SQL语句的关键字,但是这些关键字并没有参与编译,不起作用。
 */

public class JDBCTest07 {
    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;
        //单独定义变量
        String loginName = userLoginInfo.get("loginName");
        String loginPwd = userLoginInfo.get("loginPwd");

        //JDBC代码
        Connection connection = null;
        PreparedStatement ps = null;//这里使用PreparedStatement(预编译的数据库操作对象)
        ResultSet resultSet = null;

        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //3.获取预编译的数据库操作对象
            //SQL语句的框子。其中一个?,表示一个占位符,一个?将来接收一个“值”,【注意】,占位符不能使用单引号括起来。
            String  sql = "select * from t_user where loginName = ? and loginPwd = ?";
            //程序执行到此处,会发送SQL语句的框子给DBMS,然后DBMS进行SQL语句的预先编译。
            ps = connection.prepareStatement(sql);
            //给占位符?传值(第1个问号下标是1,第2个问号下标是2,JDBC中所有下标从1开始)
            ps.setString(1,loginName);
            ps.setString(2,loginPwd);
            //4.执行SQL
            resultSet = ps.executeQuery();
            //5.处理结果集
            if (resultSet.next()){
                //登录成功
                loginSuccess = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (ps != null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.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注入问题。
  • Statement是编译一次执行一次,PreparedStatement是编译一次,可执行N次,PreparedStatement效率较高一些。
  • PreparedStatement会在编译阶段做类型的安全检查。

【综上所述】:PreparedStatement使用较多,只有较少数的情况下需要使用Statement。

什么情况下必须使用Statement呢???
  • 业务方面要求必须支持SQL注入的时候
  • Statement支持SQL注入,凡是以业务方面要求是需要进行SQL语句拼接的,必须使用Statement。
演示Statement的用途

使用PreparedStatement

import java.sql.*;
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 connection = null;
        PreparedStatement  ps = null;
        ResultSet resultSet = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //获取预编译的数据库操作对象
            String sql = "select ename from emp order by ename ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,keyWords);
            //执行SQL
            resultSet = ps.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                System.out.println(resultSet.getString("ename"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                   ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

报错:
java.sql.SQLSyntaxErrorException:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以在第1行的“ desc”附近使用正确的语法

请输入desc或asc,desc表示降序,asc表示升序
请输入:
desc
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''desc'' at line 1
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
	at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
	at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
	at JDBCTest08.main(JDBCTest08.java:27)

Process finished with exit code 0

使用 Statement

import java.sql.*;
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 connection = null;
        PreparedStatement  ps = null;
        ResultSet resultSet = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //获取预编译的数据库操作对象
            String sql = "select ename from emp order by ename ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,keyWords);
            //执行SQL
            resultSet = ps.executeQuery();
            //遍历结果集
            while (resultSet.next()){
                System.out.println(resultSet.getString("ename"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                   ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }*/

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


        //执行SQL
        Connection connection = null;
        Statement  statement = null;
        ResultSet resultSet = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //获取数据库操作对象
            statement = connection.createStatement();
            //执行SQL
            String sql = "select ename from emp order by ename "+keyWords;
            resultSet = statement.executeQuery(sql);
            //遍历结果集
            while (resultSet.next()){
                System.out.println(resultSet.getString("ename"));
            }
        } catch (Exception e) {
            e.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();
                }
            }
        }
    }
}

在这里插入图片描述

PreparedStatement完成增删改

增加一条数据

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

/**
 * PreparedStatement完成 INSERT DELETE UPDATE
 */
public class JDBCTest09 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //获取预编译的数据库操作对象
            String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,60);
            ps.setString(2,"销售部");
            ps.setString(3,"上海");
            //执行SQL
            int count = ps.executeUpdate();
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (ps == null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection == null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

}

在这里插入图片描述
在这里插入图片描述
更改一条数据

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

/**
 * PreparedStatement完成 INSERT DELETE UPDATE
 */
public class JDBCTest09 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //获取预编译的数据库操作对象
            /*String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,60);
            ps.setString(2,"销售部");
            ps.setString(3,"上海");*/
            String sql = "update dept set dname = ?,loc = ? where deptno = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,"研发一部");
            ps.setString(2,"北京");
            ps.setInt(3,60);
            //执行SQL
            int count = ps.executeUpdate();
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (ps == null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection == null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

}

在这里插入图片描述
在这里插入图片描述
删除一条数据

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

/**
 * PreparedStatement完成 INSERT DELETE UPDATE
 */
public class JDBCTest09 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //获取预编译的数据库操作对象
            /*String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,60);
            ps.setString(2,"销售部");
            ps.setString(3,"上海");*/

           /* String sql = "update dept set dname = ?,loc = ? where deptno = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,"研发一部");
            ps.setString(2,"北京");
            ps.setInt(3,60);*/
            
            String sql = "delete from dept where deptno = ?";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,60);
            //执行SQL
            int count = ps.executeUpdate();
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (ps == null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection == null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

}

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

JDBC的事物自动提交机制的演示

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

/**
 * JDBC事务机制
 *      1.JDBC中的事务是自动提交的,什么是自动提交?
 *          只要执行任意一条DML语句,则自动提交一次,这是JDBC默认的事务行为。
 *          但是在实际的业务当中,通常都是N条DML语句共同联合才能完成的,必须
 *          保证他们这些DML语句在同一个事务中同时成功或者同时失败。
 *
 *      2.以下程序先来验证一下JDBC的事务是否是自动提交机制!
 *          测试结果:JDBC中只要执行任意一条DML语句,就提交一次。
 *
 */


public class JDBCTest10 {
    public static void main(String[] args) {
            Connection connection = null;
            PreparedStatement ps = null;
            try {
                //1.注册驱动
                Class.forName("com.mysql.cj.jdbc.Driver");
                //2.获取连接
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
                //3.获取预编译的数据库操作对象
                String sql = "update dept set dname = ? where deptno = ?";
                ps = connection.prepareStatement(sql);

                //第一次给占位符传值
                ps.setString(1,"x部门");
                ps.setInt(2,30);
                int count = ps.executeUpdate();//执行第一条UPDATE语句
                System.out.println(count);

                //重新给占位符传值
                ps.setString(1,"y部门");
                ps.setInt(2,20);
                count = ps.executeUpdate();//执行第二条UPDATE语句
                System.out.println(count);

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //6.释放资源
                if (ps == null) {
                    try {
                        ps.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
                if (connection == null) {
                    try {
                        connection.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }
    }

账户转账演示事务
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 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;
 *
 *    批量编辑快捷键:Alt+shift+insert
 */
public class JDBCTest11 {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //3.获取预编译的数据库操作对象
            String sql = "update t_act set balance = ? where actno = ?";
            ps = connection.prepareStatement(sql);
            //给?传值
            ps.setDouble(1,10000);
            ps.setInt(2,111);
            int count = ps.executeUpdate();
            
             //制造一个异常,这里坑定会出现空指针异常,
            // 出现异常下边的代码将会不执行,直接进入catch语句块...
            String s =null;
            s.toString();

            //给?传值
            ps.setDouble(1,10000);
            ps.setInt(2,222);
             count += ps.executeUpdate();

            System.out.println(count == 2 ?  "转账成功" : "转账失败");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if (ps == null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection == null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述
刷新数据库
在这里插入图片描述
数据丢失了!!!!

不应该出现这种现象一半成功一半失败!关闭事务自动提交机制,必须同时成功或者同时失败!

手动提交机制
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 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;
 *
 *    批量编辑快捷键:Alt+shift+insert
 *
 *    重点三行代码:
 *      connection.setAutoCommit(false);//开启事务
 *      connection.commit();//提交事务
 *      connection.rollback();//回滚事务
 */
public class JDBCTest11 {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
            //将自动提交机制改为手动提交
            connection.setAutoCommit(false);//开启事务
            //3.获取预编译的数据库操作对象
            String sql = "update t_act set balance = ? where actno = ?";
            ps = connection.prepareStatement(sql);
            //给?传值
            ps.setDouble(1,10000);
            ps.setInt(2,111);
            int count = ps.executeUpdate();

           //制造一个异常,这里坑定会出现空指针异常,
            // 出现异常下边的代码将会不执行,直接进入catch语句块...
            String s =null;
            s.toString();

            //给?传值
            ps.setDouble(1,10000);
            ps.setInt(2,222);
             count += ps.executeUpdate();

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

            //程序能够走到这里说明以上程序没有异常,事务结束,手动提交数据
            connection.commit();//提交事务
        } catch (Exception e) {
            //回滚事务
            if (connection != null){
                try {
                    connection.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            //6.释放资源
            if (ps == null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection == null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
数据是正常的!

注释掉异常之后,再刷新数据库
在这里插入图片描述
在这里插入图片描述

JDBC工具类的封装

import java.sql.*;

/**
 * JDBC工具类,简化JDBC编程。
 *
 */

public class DBUtil {
    /**
     * 工具类中的构造方法都是私有的
     * 因为工具类当中的方法都是静态的,不需要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=UTC","root","user");

    }

    /**
     * 关闭资源
     * @param connection  连接对象
     * @param statement   数据库操作对象
     * @param resultSet   结果集
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet == null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement == null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection == null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

JDBC实现模糊查询

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 ps = null;
        ResultSet resultSet = null;
        try {
            //获取连接
            connection = DBUtil.getConnection();
            //获取预编译的数据库操作对象
            
            //错误写法
            /*String sql = "select ename from emp where ename like '_?%'";
            ps = connection.prepareStatement(sql);
            ps.setString(1,"A");*/

            String sql = "select ename from emp where ename like ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,"_A%");
            resultSet = ps.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("ename"));
            }

        } catch (Exception throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            DBUtil.close(connection,ps,resultSet);
        }

    }
}

在这里插入图片描述

悲观锁和乐观锁的概念

悲观锁(行级锁 for update)和乐观锁机制
在这里插入图片描述
在这里插入图片描述

演示行级锁机制
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 这个程序开启一个事务,这个事务进行查询,并且使用行级锁/悲观锁,锁住相关的记录
 */
public class JDBCTest13 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
        //获取连接
        connection = DBUtil.getConnection();
        //开启事务
        connection.setAutoCommit(false);
        String sql = "select ename,job,sal from emp where job = ? for update ";
        ps = connection.prepareStatement(sql);
        ps.setString(1,"MANAGER");

        resultSet = ps.executeQuery();
        while (resultSet.next()){
            System.out.println(resultSet.getString("ename")+","+resultSet.getString("job")+","+resultSet.getgetDouble("sal"));

        }
        //提交事务(事务结束)
        connection.commit();

    } catch (Exception throwables) {
            if (connection == null) {
                try {
                    //回滚事务(事务结束)
                    connection.rollback();
                } catch (SQLException throwables1) {
                    throwables1.printStackTrace();
                }
            }
        throwables.printStackTrace();
    }finally {
            DBUtil.close(connection,ps,resultSet);
    }


}
}

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 ps = null;

        try {
            connection = DBUtil.getConnection();
            connection.setAutoCommit(false);

            String sql = "update emp set sal = sal * 1.1 where job = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,"MANAGER");
            int count  = ps.executeUpdate();
            System.out.println(count);
            connection.commit();

        } catch (SQLException throwables) {
            if (connection == null) {
                try {
                    connection.rollback();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            throwables.printStackTrace();
        }finally {
            DBUtil.close(connection,ps,null);
        }

    }
}

在这里插入图片描述
在这里插入图片描述
下一篇:HTML基础语法

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐