Day38

JDBC的部分明天学完,周一开始学JavaWeb,希望能在5月中旬开始学框架,加油OVO

Day38

使用开源框架的步骤

1.将jar包导入进工程

2.看帮助文档

3.调用方法使用.

JDBC的事务处理

package com.sorrymaker.Test08;

import com.sorrymaker.Test07.JDBCUtils;
import org.junit.Test;

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

/**
* 此类用于演示JDBC中的事务
* @Author nextGame
* @Date 2021/4/25 15:07
* @Version 1.0
*
* 步骤:
*     1.开启新事务:取消事务自动提交的功能
*         setAutoCommit(false)
*     2.编写组成事务的一组sql语句
*     3.结束事务
*     commit()提交
*     rollback()回滚
*
* 细节:开启事务的连接对象和获取命令的对象要一样,否则无效.
*/
public class testTransaction {
   @Test
   public void testNo() throws SQLException {
       //1.获取连接
       Connection connection = JDBCUtils.getConnection();

       //2.执行sql语句
       PreparedStatement statement = connection.prepareStatement("update account set balance =? where username =?");

       statement.setDouble(1,2000);
       statement.setString(2,"梁");

       statement.executeUpdate();

       statement.setDouble(1,6000);
       statement.setString(2,"李");

       statement.executeUpdate();

       JDBCUtils.close(null,statement,connection);
  }
   //使用事务
   @Test
   public void testTransaction(){

       Connection connection = null;
       PreparedStatement statement = null;

       try {//1.获取连接
           connection = JDBCUtils.getConnection();

           //2-1开启事务
           connection.setAutoCommit(false);

           //2-2编写sql语句,并执行
           statement = connection.prepareStatement("update account set balance =? where username =?");

           statement.setDouble(1, 1000);
           statement.setString(2, "梁");

           statement.executeUpdate();

//           //模拟异常
//           int i = 1 / 0;

           statement.setDouble(1, 7000);
           statement.setString(2, "李");

           statement.executeUpdate();

           //2-3.结束事务
           connection.commit();

      } catch (SQLException e) {
           try {
               //回滚事务
               connection.rollback();
          } catch (SQLException e1) {
               e1.printStackTrace();
          }
      } finally {
           JDBCUtils.close(null, statement, connection);
      }
  }
}

批处理

package com.sorrymaker.Test09;

import com.sorrymaker.Test07.JDBCUtils;
import org.junit.Test;

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

/**
* 使用批处理.
* 向admin添加五万行数据.
* 两个要注意的点:
*             1.url里要加上参数rewriteBatchedStatement=true
*             2.value要用values
* 向admin添加五万行数据.
* 相关API:
*         addBatch
*         executeBatch
*         clearBatch
* 说明:批处理往往和PreparedStatement一起搭配使用的,可以既减少编译次数,又减少运行次数,效率大大提高了.
* @Author nextGame
* @Date 2021/4/25 16:04
* @Version 1.0
*/
public class TestBatch {
   @Test
   //没使用批处理
   public void testNoBatch() throws SQLException {
       Connection connection = JDBCUtils.getConnection();

       PreparedStatement statement = connection.prepareStatement("insert into admin value(null,?,?)");

       for (int i = 0; i < 50001; i++) {
           statement.setString(1,"join"+i);
           statement.setString(2,"01");
           statement.executeUpdate();
      }

       JDBCUtils.close(null,statement,connection);
  }

   @Test
   //使用批处理
   public void testBatch() throws SQLException {
       Connection connection = JDBCUtils.getConnection();

       PreparedStatement statement = connection.prepareStatement("insert into admin values(null,?,?)");

       for (int i = 0; i < 50001; i++) {
           statement.setString(1,"join"+i);
           statement.setString(2,"01");
           //添加sql语句到批处理包中
           statement.addBatch();
           if(i%1000==0){
               //执行批处理包的sql语句
               statement.executeBatch();
               //清空批处理包中的sql语句
               statement.clearBatch();
          }
      }

       JDBCUtils.close(null,statement,connection);

  }
}

Blob的基本使用

package com.sorrymaker.Test10;

import com.sorrymaker.Test07.JDBCUtils;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

/**
* @Author nextGame
* @Date 2021/4/25 16:32
* @Version 1.0
*/
public class TestBlob {
   @Test
   //读取照片,存到本地.
   public void testRead() throws Exception {
       //1.获取连接
       Connection connection = JDBCUtils.getConnection();

       //2.执行修改语句
       PreparedStatement statement = connection.prepareStatement("select photo from beauty where id =1");
       ResultSet set = statement.executeQuery();
       if(set.next()){
           //方式1:
//           Blob blob = set.getBlob("photo");
//           InputStream binaryStream = blob.getBinaryStream();
           //方式2:
           InputStream inputStream = set.getBinaryStream("photo");
           FileOutputStream fos =new FileOutputStream("D:\\Desktop\\图标\\00000.png");
           int len;
           byte[] b =new byte[1024];
           while ((len=inputStream.read(b))!=-1){
               fos.write(b,0,len);
          }
           fos.close();
           inputStream.close();
      }
  }


   @Test
   //存照片
   public void testSave() throws Exception {
       //1.获取连接
       Connection connection = JDBCUtils.getConnection();

       //2.执行修改语句
       PreparedStatement statement = connection.prepareStatement("update beauty set photo =? where id =1");

       statement.setBlob(1,new FileInputStream("D:\\Desktop\\图标\\01.png"));

       int i = statement.executeUpdate();

       //3.关闭连接
       JDBCUtils.close(null,statement,connection);
  }
}

Druid数据库连接池

package com.sorrymaker.Test11;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.Period;
import java.util.Properties;

/**
* @Author nextGame
* @Date 2021/4/25 20:35
* @Version 1.0
*/
public class JDBCUtilsByDruid {
   static DataSource ds;
   static {
       try {
           Properties properties = new Properties();
           properties.load(new FileInputStream("src\\druid.properties"));
           //1.创建了一个指定参数的数据库连接池
           ds = DruidDataSourceFactory.createDataSource(properties);
           
      } catch (Exception e) {
           throw new RuntimeException(e);
      }
  }

   public static Connection getConnection() throws  Exception{
       //2.从连接池中获取可用的连接对象.
       return ds.getConnection();
  }
   public static void close(ResultSet set, Statement statement,Connection connection){
       try {
           if (set != null) {
               set.close();
          }
           if (statement != null) {
               statement.close();
          }
           if (connection != null) {
               connection.close();
          }
      } catch (Exception e) {
           throw new RuntimeException(e);
      }
  }
}

增删改查方法的封装

package com.sorrymaker.Test12;

import com.sorrymaker.Test07.JDBCUtils;
import com.sorrymaker.Test11.JDBCUtilsByDruid;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**此类用于封装通用的增删改查
* 1.执行增删改
* 2.执行查询
* @Author nextGame
* @Date 2021/4/25 20:54
* @Version 1.0
*/
public class CRUDUtils {


   /**
    * 针对于任何表的任何增删改语句
    * @param sql
    * @param params
    * @return
    * 这里的params当成一个数组来使用了
    */
   public static int update(String sql,Object...params) {
       try {
           //1.获取连接
           Connection connection = JDBCUtilsByDruid.getConnection();

           //2.执行sql语句
           PreparedStatement statement = connection.prepareStatement(sql);
           for (int i = 0; i < params.length; i++) {
               statement.setObject(i + 1, params[i]);
          }
           int update = statement.executeUpdate();
           return update;
      } catch (Exception e) {
           throw new RuntimeException(e);
      }
  }
   /**
    * 只针对Boys表,查询单条
    * 查询单行,一条记录,返回一个对象.
    * orm:Object relation mapping
    * @param sql
    * @param params
    * @return
    */
   @Test
   public static Boys querySingle(String sql,Object...params){
       Connection connection=null;

       PreparedStatement statement=null;

       ResultSet set =null;

       try {
           //1.获取连接
           connection = JDBCUtilsByDruid.getConnection();

           //2.执行查询
           statement = connection.prepareStatement(sql);

           for (int i = 0; i < params.length; i++) {
               statement.setObject(i+1,params[i]);
          }
           set = statement.executeQuery();

           if(set.next()){
               int id = set.getInt("id");
               String boyname = set.getString("boyname");
               int userCP = set.getInt("userCP");
               Boys bo =new Boys(id,boyname,userCP);
               return bo;
          }
      } catch (Exception e) {
           throw new RuntimeException(e);
      }finally {
           JDBCUtils.close(set, statement,connection);
      }
       return null;
  }

   @Test
   public static List<Boys> queryMulti(String sql, Object...params){
       Connection connection=null;

       PreparedStatement statement=null;

       ResultSet set =null;

       try {
           //1.获取连接
           connection = JDBCUtilsByDruid.getConnection();

           //2.执行查询
           statement = connection.prepareStatement(sql);

           for (int i = 0; i < params.length; i++) {
               statement.setObject(i+1,params[i]);
          }

           set = statement.executeQuery();

           List<Boys> list =new ArrayList<>();

           while (set.next()){
               int id = set.getInt("id");
               String boyname = set.getString("boyname");
               int userCP = set.getInt("userCP");
               Boys bo =new Boys(id,boyname,userCP);
               list.add(bo);
               return list;
          }
      } catch (Exception e) {
           throw new RuntimeException(e);
      }finally {
           JDBCUtils.close(set, statement,connection);
      }
       return null;
  }
}

 

posted @ 2021-04-25 22:04  独眼龙  阅读(54)  评论(0)    收藏  举报