小白也能看懂的JDBC(超详细!!!)

一、JDBC基本概念

①Java DataBase Connectivity 用java来操作数据库连接

②用统一的一套java代码操作所有的关系型数据库的一个规则(接口)

二、JDBC快速入门

1.步骤

  1. 导入jar包

  2. 注册数据库驱动

  3. 获取数据库连接对象

  4. 定义sql语句

  5. 获取执行sql语句的对象 Statement

  6. 执行sql语句,接收返回的结果

  7. 对结果进行处理

  8. 资源的释放

2.代码案例

public class demo1 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //2.注册数据库驱动
        Class.forName("com.mysql.jdbc.Driver");
        //3. 获取数据库连接对象 Connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mystudy","root","root");
        //4. 定义sql语句
        String sql = "update mytest set spwd = 111111 where id=1";
        //5. 获取执行sql语句的对象  Statement
        Statement statement = conn.createStatement();
        //6. 执行sql语句,接收返回的结果
        int i = statement.executeUpdate(sql);
        //7. 对结果进行处理
        System.out.println(i);
        //8.资源的释放
        statement.close();
        conn.close();
    }
}

三、JDBC各个接口和类的详解

1.DriverManager

注册数据库驱动

Class.forName("com.mysql.jdbc.Driver");//mysql 5以后可以省略

//源码
static {
    
    
        try {
    
    
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
    
    
            throw new RuntimeException("Can't register driver!");
        }
    }

获取数据库连接

Connection conn = DriverManager.getConnection(url,user,paassword);
url格式:jdbc:mysql://ip地址:端口号/数据库名
user格式:数据库用户名
password:密码

2. Connection

获取执行sql的语句

Statement statement = conn.createStatement();//不安全

PreparedStatement preparedStatement = conn.prepareStatement(sql);//比较安全
创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。

管理事务

//开启事务的方法---autoCommit -为 false开启事务
void setAutoCommit(boolean autoCommit)
    
//提交事务
void commit();

//回滚事务
void rollback();

/**
 * 事务管理
 */
public class demo7 {
    
    
    //修改密码的方法,同时修改赵四和admin的密码
    public static boolean update_pass(String pass){
    
    
        Connection connection = null;
        PreparedStatement preparedStatement1  = null;
        PreparedStatement preparedStatement2 = null;

        if(pass==null){
    
    
            System.out.println("输入的密码不能为空!");
            return false;
        }
        try {
    
    
            connection = jdbcUtiles.getConnection();
            connection.setAutoCommit(false); //事务已经开启
            String sql1 = "update mytest set spwd = ? where id = ?";
            String sql2 = "update mytest set spwd = ? where id = ?";

            preparedStatement1 =  connection.prepareStatement(sql1);
            preparedStatement2 =  connection.prepareStatement(sql2);

            preparedStatement1.setString(1,pass);
            preparedStatement1.setInt(2,1);

            preparedStatement2.setString(1,pass);
            preparedStatement2.setInt(2,2);

            int i = preparedStatement1.executeUpdate();
            //人为添加异常,测试事务隔离
            int k = 3/0;

            int j = preparedStatement2.executeUpdate();
            System.out.println(i);
            System.out.println(j);
            connection.commit();//提交事务
            return true;
        } catch (Exception throwables) {
    
    
            try {
    
    
                connection.rollback();//回滚
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
    
    
            jdbcUtiles.close(preparedStatement1,connection);
            jdbcUtiles.close(preparedStatement2,null);
        }
        return false;
    }

    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.println("请输入密码:");
        String pass = input.next();
        boolean b = update_pass(pass);
        if(b){
    
    
            System.out.println("成功");
        }else {
    
    
            System.out.println("失败");
        }
    }
}

3.Statement

执行静态的sql语句

boolean execute(String sql)
//可以执行任意sql语句,了解一下即可
    
int i = statement.executeUpdate(sql);
//DML语句增删改、DDL语句 创建表和库
//i代表我们的操作影响的数据库行数,可以通过i判断语句是否执行成功

ResultSet executeQuery(String sql)
//执行给定的 SQL 语句,该语句返回单个 ResultSet 对象。 

4.练习题1

//对数据库中的表进行增删改操作----完整版
public class demo2 {
    
    
    public static void main(String[] args)  {
    
    
        Connection connection = null;
        Statement statement = null;
        try {
    
    
            //获取数据库连接对象 Connection
            connection = DriverManager.getConnection("jdbc:mysql://ip地址:端口号/数据库名", "用户名", "用户密码");
            //定义sql语句
            String sql = "insert into mytest values(4,'jack',12312)";
            String sql2 = "update mytest set spwd=22222 where id=2";
            String sql3 = "delete from mytest where id = 3";
            //执行sql语句的对象  Statement
            statement = connection.createStatement();
            //执行sql语句,接收返回的结果
            int i = statement.executeUpdate(sql);
            int i2 = statement.executeUpdate(sql2);
            int i3 = statement.executeUpdate(sql3);
            System.out.println(i+i2+i3);
        } 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();
            }
        }
    }
}

5.ResultSet

//方法
boolean next();  将光标从当前位置向下移动一个

getXXX(参数); //xxx代表数据类型,参数可以是int类型,也可以string 列名

//案例 查询数据库表中信息
public class demo3 {
    
    
    public static void main(String[] args) {
    
    
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
    
    
            //获取数据库连接对象 Connection
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/mystudy","root","root");
            //定义sql语句
            String sql = "select * from mytest where id=1";
            //执行sql语句的对象  Statement
            statement = connection.createStatement();
            //执行sql语句,接收返回的结果
            resultSet = statement.executeQuery(sql);
           //判断
            if(resultSet.next()){
    
    
                int id = resultSet.getInt(1);
                String name = resultSet.getString("sname");
                String pass = resultSet.getString(3);

                System.out.println(id+"---"+name+"---"+pass);
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }
        finally {
    
    
            try {
    
    
                connection.close();
                statement.close();
                resultSet.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }
}

6.练习2:查询表中数据,并且封装代码

实体类

/**
 * 实体类------对应数据库的表
 */
public class User {
    
    
    private  int id;
    private String name;
    private String pass;

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getPass() {
    
    
        return pass;
    }

    public void setPass(String pass) {
    
    
        this.pass = pass;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pass='" + pass + '\'' +
                '}';
    }
}

工具类

为了方便,我们可以提前编写工具类

//工具类
public class jdbcUtiles {
    
    
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    static {
    
    
        //读取资源文件,获取值,执行一次
        Properties properties = new Properties();
        try {
    
    
            properties.load(new FileReader("D:\\桌面\\JDBC\\JDBC学习\\src\\jdbc.properties"));
            //获取值
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            //注册驱动
            try {
    
    
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
    
    
                e.printStackTrace();
            }

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    //获取连接对象的方法
    public static Connection getConnection() throws SQLException {
    
    
        return DriverManager.getConnection(url,user,password);
    }
    // 关闭资源的方法
    public static  void close(Statement statement,Connection connection){
    
    
        if(statement!=null){
    
    
            try {
    
    
                statement.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
    
    
            try {
    
    
                connection.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }


    // 关闭资源的方法
    public static  void close(ResultSet resultSet, Statement statement, Connection connection){
    
    
        if(statement!=null){
    
    
            try {
    
    
                statement.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
    
    
            try {
    
    
                connection.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
        if(resultSet!=null){
    
    
            try {
    
    
                resultSet.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }

    public static  void close(PreparedStatement preparedStatement,Connection connection){
    
    
        if(preparedStatement!=null){
    
    
            try {
    
    
                preparedStatement.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
    
    
            try {
    
    
                connection.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }
}

测试类

//数据库操作优化版
public class demo5 {
    
    
    public static void main(String[] args) {
    
    
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
    
    
            List<User> list = new ArrayList<>();
          connection = jdbcUtiles.getConnection();
          statement = connection.createStatement();
          String sql = "select * from mytest";
          resultSet = statement.executeQuery(sql);

            while (resultSet.next()){
    
    
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPass(resultSet.getString(3));
                list.add(user);
            }
            for(int i=0;i<list.size();i++){
    
    
                System.out.println(list.get(i));
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }finally {
    
    
            jdbcUtiles.close(resultSet,statement,connection);
        }

    }
}

注册登录练习

public class demo登录注册 {
    
    
    //登录的方法
    public static boolean Login(String usename,String password){
    
    
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        if(usename==null||password==null){
    
    
            System.out.println("用户名密码不能为空");
            return false;
        }

        try {
    
    
            connection = jdbcUtiles.getConnection();
            statement = connection.createStatement();
            String sql = "select * from mytest where sname='"+usename+"' and spwd='"+password+"'";
            resultSet = statement.executeQuery(sql);

            return resultSet.next();
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }
        return false;
    }

    //注册的方法
    public static int regiest(String usename,String password){
    
    
        Connection connection = null;
        Statement statement = null;
        if(usename==null||password==null){
    
    
            System.out.println("用户名密码不能为空");
            return 0;
        }
        try {
    
    
            connection = jdbcUtiles.getConnection();
            statement = connection.createStatement();
            String sql = "insert into mytest values(null,'"+usename+"','"+password+"')";
            int i = statement.executeUpdate(sql);
            return i;
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }
        return 0;
    }

    //测试
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = input.next();
        System.out.println("请输入密码:");
        String pass = input.next();
        //登录
        boolean login = Login(name, pass);
        if(login){
    
    
            System.out.println("登录成功!");
        }else {
    
    
            System.out.println("登录失败!");
        }

        //注册
        int regiest = regiest(name, pass);
        if(regiest==0){
    
    
            System.out.println("注册失败!");
        }else {
    
    
            System.out.println("注册成功!");
        }
    }
}

7.PreparedStatement

步骤

Statement sql注入问题 非法恶意的sql操作数据库

sql预编译,用?占位符代替参数

  • 导入jar包
  • 注册驱动
  • 获取数据库连接对象
  • 定义sql 参数采用占位符
  • 获取preparedstatement对象
  • 给?赋值(setXXX(参数1,参数2)) 参数1:位置, 参数2:值
  • 执行sql 接收返回的结果
  • 结果处理
  • 释放资源

代码案例

/**
 * PreparedStatement
 */

public class demo6 {
    
    
    public static void main(String[] args) {
    
    
        Connection connection  = null;
        PreparedStatement preparedStatement = null;
        try {
    
    
            connection = jdbcUtiles.getConnection();
            String sql="insert into mytest values(6,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,"jjj");
            preparedStatement.setString(2,"789789");
            int i = preparedStatement.executeUpdate();
            System.out.println(i);
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }finally {
    
    
            try {
    
    
                connection.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
            try {
    
    
                preparedStatement.close();
            } catch (SQLException throwables) {
    
    
                throwables.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zjdzka/article/details/111999578