栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自学之JDBC

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自学之JDBC

JDBC

(一套interface)

java Database Connectivity

java.sql.*;(该软件包下的接口)

MySQL数据库厂家负责编写JDBC的实现类—MySQL驱动

驱动:所有的数据库的驱动的都是以jar包的形式存在,jar包中有很多.class文件,这些class文件就是对JDBC接口的实现。驱动不是sun公司提供,是各大数据库厂家负责提供,下载驱动jar包需要去各大数据库官网下载。

实现类被称为驱动。

JDBC编程六步

注册驱动、获取连接、获取数据库操作对象,执行sql语句、处理查询结果集、释放资源

url:包括 协议 IP port 资源名

http://182.61.200.7:80/index.html

http://通信协议

182.61.200.7:服务器IP

80:服务器软件端口

index.html

注册驱动

第一种方式:

package jdbc;

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

public class JdbcTest02 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //1、注册驱动
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","123456");
            //3、获取数据库操作对象
            stmt = conn.createStatement();
            //4、执行SQL语句
            String sq1 = "delete from dept where deptno = 50";
            int count = stmt.executeUpdate(sq1);
            System.out.println(count==1?"删除成功":"删除失败");

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //6.释放资源
            if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                if (conn!=null){
                    try {
                        conn.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }
    }
}

JDBC里的sql语句不需要加分号。

第二种方式:

package jdbc;

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


public class JdbcTest03 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //1、注册驱动
            //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //注册驱动的第二种方式:常用的
            //为什么常用?因为参数是一个字符串,字符串可以写到xxx.properties文件中
            //一下方法不需要接收返回值,因为我们只想用它的类加载动作
            Class.forName("com.mysql.jdbc.Driver");
            //2、获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","123456");
            System.out.println(conn);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
url:orcl?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
-- 处理查询结果集
ResultSet s = null;
rs = stmt.executeQuery(sql);

package jdbc;
import java.sql.*;
public class JdbcTest05 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        //1.注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","123456");
        //3.获取数据库操作对象
            stmt = conn.createStatement();
        //4.执行sql
            String sql = "select empno as a,ename,sal from emp";
            //int executeUpdate(insert/delete/update)
            rs = stmt.executeQuery(sql);//专门执行DQL语句的方法
        //5.处理查询结果集
            while (rs.next()){
                String empno = rs.getString(1);
                String ename = rs.getString(2);
                String sal = rs.getString(3);
                System.out.println(empno+","+ename+","+sal);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }if (stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

SQL注入现象 1.根本原因:

用户输入的信息中含有sql语句的关键字,并且这些关键字参与sql语句的编译过程,

导致sql语句的原意被扭曲,进而达到sql注入

2.解决:

只要用户提供的信息不参与SQL语句的编译过程,问题就解决了。

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

要想用户信息不参与SQL语句的编译,那么必须使用java.sql.PreparedStatement

PreparedStatement继承了java.sql.Statement

PreparedStatement属于预编译的数据库操作对象

PreparedStatement的原理是:预先对sql语句的框架进行编译,然后再给sql语句传"值";

解决SQL注入的关键是什么?

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

package jdbc;

import java.sql.*;

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


public class JdbcTest06 {
    public static void main(String[] args) {
       //初始化一个界面
        Map userLoginInfo = initUI();
        //验证用户名和密码
        boolean loginSuccess = login(userLoginInfo);
        //最后输出结果
        System.out.println(loginSuccess ? "登陆成功":"登陆失败");
    }



    
    private static Map initUI() {
        Scanner s = new Scanner(System.in);
        System.out.println("用户名:");
        String loginName = s.nextLine();

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

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

        return userLoginInfo;
    }

private static boolean login(Map userLoginInfo) {
    //打标记
    boolean loginSuccess = false;
    //单独定义变量
    String loginName = userLoginInfo.get("loginName");
    String loginPwd = userLoginInfo.get("loginPwd");
    //JBDC代码
    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/orcl","root","123456");
        //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 throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps != null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    return loginSuccess;
}


}

3.对比Statement和PreparedStatement

Statement存在sql注入问题,PreparedStatement解决了sql注入问题

Statement编译一次执行一次,PreparedStatement编译一次,可执行N次。PreparedStatement效率较高一些

PreparedStatement会在编译阶段做类型的安全检查。

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

4.必须使用Statement:

业务方面必须支持SQL注入的时候。

Statement支持SQL注入,凡是业务方面要求是需要sql语句拼接的,必须使用Statement。

JDBC事务
package jdbc;

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


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

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

            ps.setString(1,"y部门");
            ps.setInt(2,20);
            count = ps.executeUpdate();//执行第二条update语句
            System.out.println(count);
            //4.执行SQL语句
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

账户转账演示事务

package jdbc;

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


public class JDbcTest10 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","123456");
            //将自动提交机制改为手动提交
            conn.setAutoCommit(false);//开启事务

            //3.获取预编译的数据库操作对象
            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();
            //给?传值
            ps.setDouble(1,10000);
            ps.setInt(2,222);
            count += ps.executeUpdate();
            System.out.println(count == 2?"转账成功":"转账失败");

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

JDBC工具类的封装
package jdbc.utils;
import java.sql.*;
import java.sql.Connection;


public class DButil {
    
    private DButil(){}
    //静态代码块在类加载时执行,只执行一次
    static {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    
    public static Connection getConnection() throws SQLException {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/orcl","root","123456");
            return conn;
    }

    
    public static void close(Connection conn,Statement ps,ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }if(ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

案例:模糊查询
package jdbc;

import jdbc.utils.DButil;

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


public class JdbcTest11 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = DButil.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 (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            DButil.close(conn,ps,rs);
        }
    }
}

悲观锁和乐观锁

悲观锁:事务必须排队执行。数据锁住了,不允许并发。(行级锁:select 后面添加for update)

乐观锁:支持并发,事务也不需要排队,只不过需要版本号。

事务1—>读取到版本号1.1

事务2—>读取到版本号1.1

其中事务1先修改了,修改之后看了版本号是,1.1,于是提交修改的数据,将版本号修改为1.2

其中事务2后修改的,修改之后准备提交的时候,发现版本号为1.2,和它最初的版本号不一致。回滚。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573111.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号