• 【Mysql】第5篇--JDBC


    DCL:数据控制语言

    mysql -h192.168.141.75 -urose -prose	
    
    为mysql数据库管理系统创建多用户: 登录root帐号
    		create user 'user1'@'localhost' identified by '密码';
    		create user 'user2'@'%' identified by 'user2';
    	为用户分配权限:
    		分配指定权限:
    		grant create,alter,drop,insert,update,delete,select on test.* to 'user1'@'localhost';
    		分配所有权限:
    		grant all on *.* to 'user2'@'%';
    	
    	查看权限:
    		show grants for 'user1'@'localhost';
    	撤销权限:
    		revoke all on test.* from 'user1'@'localhost';
    	删除用户:
    		drop user 'user2'@'%';
    	修改密码:
    		修改root帐号,在未登录mysql下进行
    		mysqladmin -uroot -p password 新密码 -- 新密码不需要加上引号
    		修改普通帐号: 登录该帐号下进行
    		set password for '用户名'@'主机名' = password('新密码');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    JDBC

    操作mysql数据库:
    	DOS窗口:
    	sqlyog:
    	jdbc: java代码操作mysql数据库的手段
    
    
    数据库分类:
    	关系型数据库: Mysql Oracle
    		在存放数据时,数据和数据之间有一定的关联关系
    		将数据存放在硬盘上
    	非关系型数据库: redis
    		在存放数据时,数据和数据之间没有关联关系,类似于map集合   key=value
    		将数据存放在内存中
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    概述

    ​ JDBC是一种用于执行SQL语句的Java API,可以为多种关系型数据库提供统一访问,它由一组用Java语言编写的类和接口组成

    ​ JDBC是操作关系型数据库的规范.

    ​ 接口: 规范

    入门案例

    查询所有商品表中的信息.

    ​ 1.注册驱动

    ​ 2.获取连接

    ​ 3.编写sql

    ​ 4.获取语句的执行者

    ​ 5.执行sql并返回结果集

    ​ 6.处理结果集

    ​ 7.释放资源

    public class JDBCDemo {
        public static void main(String[] args) throws Exception {
            //0.导入mysql的驱动包
            //a.在模块下创建lib文件夹
            //b.将驱动包放入lib文件夹中
            //c.在lib文件夹上 或 指定jar包上右击 add as lib...(将jar包加入当前环境)
            //1.注册驱动:将实现类加载到内存中
            //驱动:实现类
            DriverManager.registerDriver(new Driver());//将驱动类交给DriverManager管理
            /**
             * 通过查看mysql提供的实现类Driver源码
             * 我们会发现在实现类中的静态代码块内,已经将自己注册给了DriverManager
             * 我们若再注册就重复注册
             */
            
            
            Typora
            
            //编译异常
            //new Driver();
            //运行时异常(将异常推迟)
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/31801";
            String uesrname = "root";
            String password = "root";
            Connection conn = DriverManager.getConnection(url,uesrname,password);
            //3.编写sql语句
            String sql = "select * from product";
            //4.创建语句执行者(小货车)
            Statement st = conn.createStatement();
            //5.执行sql返回结果集
            ResultSet rs = st.executeQuery(sql);
            //6.处理结果集
            while (rs.next()){
                    //rs中存到的是当前行的数据信息
                    //通过类型和字段名称获取信息
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                System.out.println(id+":"+name+":"+price);
            }
            //7.释放资源
            rs.close();
            st.close();
            conn.close();
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    JDBC API详解

    Driver:接口

    ​ 每个驱动程序类必须实现的接口

    ​ mysql的驱动类需要实现该接口,遵循规范.

    DriverManager:类

    管理一组 JDBC 驱动程序的基本服务。

    常用方法:

    ​ static void registerDriver(Driver driver); // 注册驱动(将mysql的驱动类加载到内存)

    ​ Class.forName(“com.mysql.jdbc.Driver”); ★★★

    ​ static Connection getConnection(String url, String user, String password); // 建立java代码和mysql的连接

    ​ 获取一个和数据库连接的对象

    ​ url:数据库的指定位置
    ​ jdbc:mysql://localhost:3306/数据库名称

    ​ jdbc:mysql://localhost:3306/数据库名称?characterEncoding=utf8

    ​ user:用户名

    ​ password:密码

    Connection:接口

    ​ Statement createStatement();获取语句的执行者(小货车)

    ​ ★★PreparedStatement prepareStatement(String sql); 获取预编译语句的执行者 (明天内容)

    ​ void setAutoCommit(boolean autoCommit) ;
    ​ false:开启事务, ture:关闭事务(关闭手动事务)

    ​ void commit();
    ​ 提交事务

    ​ void rollback();
    ​ 回滚事务

    Statement:接口

    ​ boolean execute(String sql) (了解)
    此方法可以执行任意sql语句。返回boolean值,表示是否返回ResultSet结果集。仅当执行select语句,且有
    ​ 返回结果时返回true, 其它语句都返回false;

    ​ ResultSet executeQuery(String sql);执行查询 ★★★

    ​ int executeUpdate(String sql); 执行添加,修改,删除 返回的是影响的条数 ★★★

    Resultset:接口

    ​ next(); 判断是否有下一条数据
    ​ 返回Boolean值

    ​ getXxx(“string 字段名称” | int 第几列);
    ​ Xxx:可以为多种数据类型

    ​ 常见的有:

    ​ getInt()

    ​ getString()

    ​ getObject()

    ​ 参数:

    ​ int:列数(第几列)

    ​ String:字段名称

    异常:
    	在java中java代码出现的异常最终都会被捕获.
        什么时候抛:
    		如果调用者有需求,需要判断异常,然后进行对异常处理时,需要抛
    		
    	什么时候抓:
    		异常一般都在最终的代码中捕获(main方法)
    快捷方式: 
    	选中可能存在异常的代码  按  ---> 
    	ctrl + alt + t 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    完成jdbc对数据库的CURD(增删改查)

    对帐号表进行增删改查
    public class jdbcCurd {
        public static void main(String[] args) throws Exception {
    //        查询
           select();
            //添加
            //insert();
            //修改
            //update();
            //删除
            //delete();
        }
    
        private static void delete() throws ClassNotFoundException, SQLException {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/31801";
            String username = "root";
            String password = "root";
            Connection conn = DriverManager.getConnection(url, username, password);
            //3.编写sql语句
            String sql = "delete from product where id = 6";
            //4.获取语句执行者
            Statement st = conn.createStatement();
            //5.执行sql语句
            int count = st.executeUpdate(sql);
            //6.将执行结果打印出来
            System.out.println(count);
            //7. 释放资源
            st.close();
            conn.close();
        }
    
        private static void update() throws ClassNotFoundException, SQLException {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/31801";
            String username = "root";
            String password = "root";
            Connection conn = DriverManager.getConnection(url, username, password);
            //3.编写sql语句
            String sql = "update product set name = '大幂幂' where id = 4";
            //4.获取语句执行者
            Statement st = conn.createStatement();
            //5.执行sql语句
            int i = st.executeUpdate(sql);
            //6.查看结果集
            System.out.println(i);
            //7.释放资源
            st.close();
            conn.close();
    
    
        }
    
        /**
         * 添加商品信息
         */
        private static void insert() throws Exception {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/31801";
            String username = "root";
            String password = "root";
            Connection conn = DriverManager.getConnection(url, username, password);
            //3.编写sql语句
            String sql = "insert into product values(null,'辣条',10)";
            //4.获取语句执行者
            Statement st = conn.createStatement();
            //5.执行sql语句并返回结果
            int count = st.executeUpdate(sql);
            //6.处理结果集
            System.out.println(count);
            //7.释放资源
            st.close();
            conn.close();
    
    
        }
    
        /**
         * 完成查询商品信息
         */
        private static void select() throws Exception {
            //1.注册驱动:将驱动类加载到内存,将DriverManager管理
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/31801";
            String username = "root";
            String password = "root";
            Connection conn = DriverManager.getConnection(url, username, password);
            //3.编写sql语句
            String sql = "select * from product";
            //4.获取语句执行者
            Statement st = conn.createStatement();
            //5.执行sql语句并返回结果集
            ResultSet rs = st.executeQuery(sql);
            //6.处理结果集
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                System.out.println(id + " : " + name + " : " + price);
            }
            //7.释放资源
            rs.close();
            st.close();
            conn.close();
    
        }
    }
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115

    工具类封装:

    public class JDBCUtils {
    
        private static Connection conn;
        static {
            try {
                //注册驱动
                Class.forName("com.mysql.jdbc.Driver");
                //2.获取连接
                String url = "jdbc:mysql://localhost:3306/31801";
                String username = "root";
                String password = "root";
                conn = DriverManager.getConnection(url, username, password);
                  } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        //1.提供获取连接的方法
        public static Connection getConnection(){
            return conn;
        }
            //2.提供释放资源的方法
            public static void close(ResultSet rs,Statement st,Connection conn){
                try {
                    if(rs!=null){
                        rs.close();
                    }
                    if(st!=null){
                        st.close();
                    }
                    if(conn!=null){
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            // 重载方法 同名不同参,与返回值无关
            public static void close(Statement st,Connection conn){
                close(null,st,conn);
            }
        }
    
    
    更换数据库会修改工具类,将工具类抽取成配置文件
    
    # key = value
    jdbc.driver = com.mysql.jdbc.Driver
    jdbc.url = jdbc:mysql://localhost:3306/31801
    jdbc.username = root
    jdbc.password = root
    public class JDBCUtils {
    
        private static Connection conn;
        static {
            try {
                //将properties配置文件放在src目录文件下
    
                //解析配置文件获取可变参数
                //获取配置文件的输入流信息
                InputStream is = JDBCUtils.class.getResourceAsStream("/jdbc.properties");
                //解析配置文件获取键值对
                Properties prop = new Properties();
                prop.load(is);
                //从prop中获取值的信息
                String driver = prop.getProperty("jdbc.driver");
                String url = prop.getProperty("jdbc.url");
                String username = prop.getProperty("jdbc.username");
                String password = prop.getProperty("jdbc.password");
                //System.out.println(driver+ " : " + url + ":" + username + ":" +password );
    
    
                //1.注册驱动
                Class.forName(driver);
                //2.获取连接
                conn = DriverManager.getConnection(url,username,password);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    //1.提供获取连接的方法
    public static Connection getConnection(){
        return conn;
    }
        //2.提供释放资源的方法
        public static void close(ResultSet rs,Statement st,Connection conn){
            try {
                if(rs!=null){
                    rs.close();
                }
                if(st!=null){
                    st.close();
                }
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 重载方法
        public static void close(Statement st,Connection conn){
            close(null,st,conn);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107

    模拟用户登录功能:

    需求分析:
    	程序启动后,提示用户输入用户名和密码,当用户输入完毕后,获取用户输入的用户名和密码,使用JDBC查询数据库,如果正确,则登录成功,如果用户名或密码错误,则登录失败.	
    技术分析:
    	Scanner 
    	JDBC:
    		sql="SELECT * FROM USER WHERE username = '"+username+"' AND PASSWORD='"+password+"'";
    步骤分析:
    	1.提示用户输入用户名和密码
    	2.获取用户输入的用户名和密码
    	3.使用JDBC查询数据库完成登录
    	4.判断执行结果
    	
    	
    	public class LoginDemo {
        public static void main(String[] args)  {
            try {
            //用来获取控制台输入的内容
                Scanner scanner = new Scanner(System.in);
                //    1.提示用户输入用户名和密码
                System.out.println("请输入您的用户名:");
                String username = scanner.nextLine();
                System.out.println("请输入密码:");
                String password = scanner.nextLine();
                //	2.获取用户输入的用户名和密码
                //	3.使用JDBC查询数据库完成登录
                //a 从工具类中获取链接
                Connection conn = JDBCUtils.getConnection();
                //b.编写sql语句
                String sql = "select * from user where username = '"+username+"'and password = '"+password+"'";
                //c.获取语句执行者
                Statement st = conn.createStatement();
                //d.执行sql并返回结果
                ResultSet rs = st.executeQuery(sql);
                //	e.判断执行结果
                if(rs.next()){
                    //登录成功
                    System.out.println("恭喜<"+ username+">登录成功");
                }else {
                    System.out.println("用户名或密码错误");
                }
                //f.释放资源
                JDBCUtils.close(rs,st,conn);
            } catch (SQLException e) {
                System.out.println("当前功能正在维护....");
            }
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    jdbc中的事务控制:

    事务: 逻辑上的一组操作,要么同时成功,要么同时失败
    
    案例: 转账
    	tom: 1000
        rose: 1000
        让tom给rose转100
    
    API: connection对象
    
    	void setAutoCommit(boolean autoCommit) ;
    		false:开启手动事务(关闭自动事务)
    		ture:关闭手动事务(开启自动事务)
    
    	void commit();
    	提交事务
    
    	void rollback();
    	回滚事务
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    public class TransactionDemo {
        /**
         * 转账
         *  tom 给rose转账100
         *  从tom账号上减100
         *  给rose账号上加100
         *
         * @param args
         */
    
        public static void main(String[] args) throws SQLException {
            Connection conn = null;
            Statement st = null;
            try {
                //1.获取连接
                 conn = JDBCUtils.getConnection();
                //===========关闭mysql 自动事务提交(开启手动事务提交)
                conn.setAutoCommit(false);
                //2.编写sql语句
                String sql1 = "update account set money = money-100 where name = 'tom'";
                String sql2 = "update account set money = money+100 where name = 'rose'";
                //获取语句执行者
                st = conn.createStatement();
                //执行sql 并返回结果集
                int count1 = st.executeUpdate(sql1);
                //模拟异常
               // System.out.println(1/0);
                int count2 = st.executeUpdate(sql2);
                //处理结果
                System.out.println(count1+":" +count2);
                //手动提交事务
                conn.commit();
    
            } catch (Exception e) {
                //回滚事务
                conn.rollback();
            }finally {
                //6.释放资源
                JDBCUtils.close(st,conn);
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    总结:

    DCL: 数据控制语言
    	操作用户和权限
    JDBC: java操作mysql数据库的手段
    	java操作关系型数据库的规范(接口)
    API:
    	Driver: 接口 (数据库厂商需要实现该接口)
    	DriverManager: 类
    		注册驱动方法
    		getConnection(url,username,paasword);
    	Connection: 接口
    		createStatement();
    		setAutoCommit(false);
    		commit();
    		rollback();
    	Statement: 接口 语句执行者
    		ResultSet executeQuery(sql); 执行查询
    		int executeUpdate(sql); 执行增删改
    	ResultSet: 接口
    		next();
    		getXxx(String 字段名|int 第几列);
    JDBC:
    	1.注册驱动
    	2.获取连接
    	3.编写sql语句
    	4.获取语句执行者
    	5.执行sql并返回结果集
    	6.处理结果集
    	7.释放资源
    JDBC带有手动事务:
    	1.注册驱动
    	2.获取连接
    	// 关闭自动事务提交(开启手动事务提交)
    	3.编写sql语句
    	4.获取语句执行者
    	5.执行sql并返回结果集
    	6.处理结果集
    	// 提交事务 | 回滚事务
    	
    	7.释放资源
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
  • 相关阅读:
    Kotlin 开发Android app(八):Kotlin类对象class
    【c语言】100行代码搞定电子琴
    76~90(正则表达式)
    Day49 力扣单调栈 : 739. 每日温度 |496.下一个更大元素 I
    Xylan-PEG-NHS|木聚糖-聚乙二醇-琥珀酰亚胺
    保姆级 Keras 实现 Faster R-CNN 十三 (训练)
    CompletableFuture 异步编排、案例及应用小案例
    STM32 CAN 滤波为什么要左移5位
    Redis Key-Value数据库 【实战】
    Java类加载器
  • 原文地址:https://blog.csdn.net/qq_41250372/article/details/125462413