JDBC

一.概念

​ Java数据库的连接(Java访问数据库的规范)

二.作用

​ 用来执行sql语句的API

三.使用

1.注册驱动:DriverManager


          static {//随着类的加载而加载而且只会加载一次
          try {
              Properties properties = new Properties();
              InputStream is =                                                                           JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");//表示在src下           的
             properties.load(is);
              String driver = properties.getProperty("driver");
              url = properties.getProperty("url");
              username = properties.getProperty("username");
              password = properties.getProperty("password");
              Class.forName(driver);
          } catch (IOException e) {
              e.printStackTrace();
          } catch (ClassNotFoundException e) {
              e.printStackTrace();
          }
      }

2.获取连接:Connection

connection = DriverManager.getConnection(url, username, password);

3.创建SQL语句平台(执行SQL语句对象):Statement

  Statement statement = connection.createStatement();

4.执行SQL语句:DML(executeUpdate,),DQL(executeQuEry)

  String sql ="SELECT * FROM USER WHERE NAME ='"+username+"' AND password = '"+password+"'";

5.处理结果集RESULTSET

boolean execute = statement.execute(sql);

6.释放资源CLOSE

 try {
      if (resultSet != null) {
          resultSet.close();
      }
  } catch (SQLException e) {
      e.printStackTrace();
  }
  try {
      if (statement != null) {
          statement.close();
      }
  } catch (SQLException e) {
      e.printStackTrace();
  }
  try {
      if (connection != null) {
          connection.close();
      }
  } catch (SQLException e) {
      e.printStackTrace();
  }

四.事物TRANSACTION

注册驱动

获取连接

获取到Statement

开启事务

使用Statement执行SQL

提交或回滚事务

关闭资源

转账案例:

Connection connection = null;
        Statement statement = null;
        try {
            connection= JDBCUtils.getConnection();
            statement = connection.createStatement();
            connection.setAutoCommit(false);//开启事物
            int a = 1/0;
            String sql = "update account SET balance = balance - 100 WHERE NAME ='张三';";
            int i = statement.executeUpdate(sql);
//            connection.commit();
            connection.rollback();
            System.out.println("+++"+i);
        } catch (SQLException e) {
            e.printStackTrace();
        }
            JDBCUtils.close(null,statement,connection);
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值