14. JDBC

空~2022年8月29日
  • JavaWeb
大约 5 分钟

14. JDBC

什么是 JDBC : Java 连接数据库!

1568439601825

需要 jar 包的支持:

  • java.sql
  • javax.sql
  • mysql-conneter-java… 连接驱动(必须要导入)

实验环境搭建:

CREATE TABLE users(
    id INT PRIMARY KEY,
    `name` VARCHAR(40),
    `password` VARCHAR(40),
    email VARCHAR(60),
    birthday DATE
);

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');


SELECT * FROM users;

导入数据库依赖

<!--mysql的驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

IDEA 中连接数据库:

1568440926845

JDBC 固定步骤

  1. 加载驱动
  2. 连接数据库,代表数据库
  3. 向数据库发送 SQL 的对象 Statement : CRUD
  4. 编写 SQL (根据业务,不同的 SQL)
  5. 执行 SQL
  6. 关闭连接
public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
        Statement statement = connection.createStatement();

        //4.编写SQL
        String sql = "select * from users";

        //5.执行查询SQL,返回一个 ResultSet  : 结果集
        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()){
            System.out.println("id="+rs.getObject("id"));
            System.out.println("name="+rs.getObject("name"));
            System.out.println("password="+rs.getObject("password"));
            System.out.println("email="+rs.getObject("email"));
            System.out.println("birthday="+rs.getObject("birthday"));
        }

        //6.关闭连接,释放资源(一定要做) 先开后关
        rs.close();
        statement.close();
        connection.close();
    }
}

预编译 SQL

public class TestJDBC2 {
    public static void main(String[] args) throws Exception {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.编写SQL
        String sql = "insert into  users(id, name, password, email, birthday) values (?,?,?,?,?);";

        //4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
        preparedStatement.setString(2,"狂神说Java");//给第二个占位符? 的值赋值为狂神说Java;
        preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
        preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为1;
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());

        //5.执行SQL
        int i = preparedStatement.executeUpdate();

        if (i>0){
            System.out.println("插入成功@");
        }

        //6.关闭连接,释放资源(一定要做) 先开后关
        preparedStatement.close();
        connection.close();
    }
}

事务

要么都成功,要么都失败!

ACID 原则:保证数据的安全。

开启事务
事务提交  commit()
事务回滚  rollback()
关闭事务

转账:
A:1000
B:1000

A(900)   --100-->   B(1100)

Junit 单元测试

依赖

<!--单元测试-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

简单使用

@Test 注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!

@Test
public void test(){
    System.out.println("Hello");
}

1568442261610

失败的时候是红色:

1568442289597

搭建一个环境:

CREATE TABLE account(
   id INT PRIMARY KEY AUTO_INCREMENT,
   `name` VARCHAR(40),
   money FLOAT
);

INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
@Test
public void test() {
    //配置信息
    //useUnicode=true&characterEncoding=utf-8 解决中文乱码
    String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
    String username = "root";
    String password = "123456";

    Connection connection = null;

    //1.加载驱动
    try {
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
         connection = DriverManager.getConnection(url, username, password);

        //3.通知数据库开启事务,false 开启
        connection.setAutoCommit(false);

        String sql = "update account set money = money-100 where name = 'A'";
        connection.prepareStatement(sql).executeUpdate();

        //制造错误
        //int i = 1/0;

        String sql2 = "update account set money = money+100 where name = 'B'";
        connection.prepareStatement(sql2).executeUpdate();

        connection.commit();//以上两条SQL都执行成功了,就提交事务!
        System.out.println("success");
    } catch (Exception e) {
        try {
            //如果出现异常,就通知数据库回滚事务
            connection.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

封装 JDBC 工具类

工具类

public class JDBCUtils {

  private static String driver;
  private static String url;
  private static String username;
  private static String password;

  static {
    try {
      // 方式一.可以直接赋值,需要编译后,才能执行
//            driver = "com.mysql.jdbc.Driver";
//            url = "jdbc:mysql://localhost:3306/bjpowernode";
//            username = "root";
//            password = "1234";
      // 方式二:将数据放在不需要编译就可以直接运行的文件中,properties文件
      Properties properties = new Properties();
//            properties.load(new FileInputStream("src//db.properties"));
      properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"));
      // 为成员变量赋值
      driver = properties.getProperty("jdbc.driver");
      url = properties.getProperty("jdbc.url");
      username = properties.getProperty("jdbc.username");
      password = properties.getProperty("jdbc.password");

      Class.forName(driver);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 返回连接数据库的对象
   *
   * @return
   */
  public static Connection getConnection() {
    try {
      return DriverManager.getConnection(url, username, password);
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }
    return null;
  }

  /**
   * 关闭资源
   *
   * @param connection
   * @param preparedStatement
   * @param resultSet
   */
  public static void closeAll(Connection connection, PreparedStatement preparedStatement,
      ResultSet resultSet) {
    if (resultSet != null) {
      try {
        resultSet.close();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
    }
    if (preparedStatement != null) {
      try {
        preparedStatement.close();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
    }
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
    }

  }


  /**
   * 对于JDBC工具类封装可以根据需要进行不同的处理, 原则上可以将JDBC操作的6个步骤,全部封装在工具类中,
   * <p>
   * 对于所有的DML语句进行封装处理
   *
   * @param sql  要执行的DML语句
   * @param args sql语句中占位符的数据值
   */
  public static int myExecuteUpdate(String sql, Object... args) {
    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    int result = -1;
    try {
      connection.setAutoCommit(false);

      preparedStatement = connection.prepareStatement(sql);
      // 判断是否存在占位符
      if (args != null) {
        // 为占位符赋值
        for (int i = 0; i < args.length; i++) {
          preparedStatement.setObject(i + 1, args[i]);
        }
      }
      result = preparedStatement.executeUpdate();
    } catch (Exception throwables) {
      try {
        connection.rollback();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      throwables.printStackTrace();
    } finally {
      try {
        connection.commit();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
      closeAll(connection, preparedStatement, null);
    }
    return result;
  }
}

配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bjpowernode
jdbc.username=root
jdbc.password=root