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

image.png

需要jar包的支持:

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

    实验环境搭建

  1. CREATE TABLE users(
  2. id INT PRIMARY KEY,
  3. `name` VARCHAR(40),
  4. `password` VARCHAR(40),
  5. email VARCHAR(60),
  6. birthday DATE
  7. );
  8. INSERT INTO users(id,`name`,`password`,email,birthday)
  9. VALUES(1,'张三','123456','zs@qq.com','2000-01-01');
  10. INSERT INTO users(id,`name`,`password`,email,birthday)
  11. VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
  12. INSERT INTO users(id,`name`,`password`,email,birthday)
  13. VALUES(3,'王五','123456','ww@qq.com','2000-01-01');
  14. SELECT * FROM users;

导入数据库依赖

  1. <!--mysql的驱动-->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>5.1.47</version>
  6. </dependency>

IDEA中连接数据库:

image.png

JDBC 固定步骤:

  1. 加载驱动
  2. 连接数据库,代表数据库
  3. 向数据库发送SQL的对象Statement : CRUD
  4. 编写SQL (根据业务,不同的SQL)
  5. 执行SQL
  6. 关闭连接
  1. public class TestJdbc {
  2. public static void main(String[] args) throws ClassNotFoundException, SQLException {
  3. //配置信息
  4. //useUnicode=true&characterEncoding=utf-8 解决中文乱码
  5. String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
  6. String username = "root";
  7. String password = "123456";
  8. //1.加载驱动
  9. Class.forName("com.mysql.jdbc.Driver");
  10. //2.连接数据库,代表数据库
  11. Connection connection = DriverManager.getConnection(url, username, password);
  12. //3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
  13. Statement statement = connection.createStatement();
  14. //4.编写SQL
  15. String sql = "select * from users";
  16. //5.执行查询SQL,返回一个 ResultSet : 结果集
  17. ResultSet rs = statement.executeQuery(sql);
  18. while (rs.next()){
  19. System.out.println("id="+rs.getObject("id"));
  20. System.out.println("name="+rs.getObject("name"));
  21. System.out.println("password="+rs.getObject("password"));
  22. System.out.println("email="+rs.getObject("email"));
  23. System.out.println("birthday="+rs.getObject("birthday"));
  24. }
  25. //6.关闭连接,释放资源(一定要做) 先开后关
  26. rs.close();
  27. statement.close();
  28. connection.close();
  29. }
  30. }

预编译SQL

  1. public class TestJDBC2 {
  2. public static void main(String[] args) throws Exception {
  3. //配置信息
  4. //useUnicode=true&characterEncoding=utf-8 解决中文乱码
  5. String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
  6. String username = "root";
  7. String password = "123456";
  8. //1.加载驱动
  9. Class.forName("com.mysql.jdbc.Driver");
  10. //2.连接数据库,代表数据库
  11. Connection connection = DriverManager.getConnection(url, username, password);
  12. //3.编写SQL
  13. String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);";
  14. //4.预编译
  15. PreparedStatement preparedStatement = connection.prepareStatement(sql);
  16. preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
  17. preparedStatement.setString(2,"狂神说Java");//给第二个占位符? 的值赋值为狂神说Java;
  18. preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
  19. preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为1;
  20. preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());
  21. //5.执行SQL
  22. int i = preparedStatement.executeUpdate();
  23. if (i>0){
  24. System.out.println("插入成功@");
  25. }
  26. //6.关闭连接,释放资源(一定要做) 先开后关
  27. preparedStatement.close();
  28. connection.close();
  29. }
  30. }

事务

要么都成功,要么都失败!
ACID原则:保证数据的安全。

  1. 开启事务
  2. 事务提交 commit()
  3. 事务回滚 rollback()
  4. 关闭事务
  5. 转账:
  6. A:1000
  7. B:1000
  8. A(900) --100--> B(1100)

Junit单元测试

依赖

  1. <!--单元测试-->
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.12</version>
  6. </dependency>

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

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

image.png

失败的时候是红色:
image.png

搭建一个环境

  1. CREATE TABLE account(
  2. id INT PRIMARY KEY AUTO_INCREMENT,
  3. `name` VARCHAR(40),
  4. money FLOAT
  5. );
  6. INSERT INTO account(`name`,money) VALUES('A',1000);
  7. INSERT INTO account(`name`,money) VALUES('B',1000);
  8. INSERT INTO account(`name`,money) VALUES('C',1000);
  1. @Test
  2. public void test() {
  3. //配置信息
  4. //useUnicode=true&characterEncoding=utf-8 解决中文乱码
  5. String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
  6. String username = "root";
  7. String password = "123456";
  8. Connection connection = null;
  9. //1.加载驱动
  10. try {
  11. Class.forName("com.mysql.jdbc.Driver");
  12. //2.连接数据库,代表数据库
  13. connection = DriverManager.getConnection(url, username, password);
  14. //3.通知数据库开启事务,false 开启
  15. connection.setAutoCommit(false);
  16. String sql = "update account set money = money-100 where name = 'A'";
  17. connection.prepareStatement(sql).executeUpdate();
  18. //制造错误
  19. //int i = 1/0;
  20. String sql2 = "update account set money = money+100 where name = 'B'";
  21. connection.prepareStatement(sql2).executeUpdate();
  22. connection.commit();//以上两条SQL都执行成功了,就提交事务!
  23. System.out.println("success");
  24. } catch (Exception e) {
  25. try {
  26. //如果出现异常,就通知数据库回滚事务
  27. connection.rollback();
  28. } catch (SQLException e1) {
  29. e1.printStackTrace();
  30. }
  31. e.printStackTrace();
  32. }finally {
  33. try {
  34. connection.close();
  35. } catch (SQLException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }