JDBC学习笔记

获取数据库连接的五种方式:

 

 

方式五【最终版】只练这一种也可以(doge):

把基本信息放到一个配置文件当中去。

 

 方式五的好处: 


1.实现了数据与代码的分离,实现了解耦

2.如果需要修改配置文件信息,可以避免程序的重新打包【意思就是避免了进行修改我们的代码,而是去直接进行修改配置文件】

 PreparedStatement与Statement:

 PreparedStatement是Statement的子接口,但是我们使用的是 PreparedStatement;

PreparedStatement可以提前进行预编译的操作

所以说PreparedStatement解决了sql注入的问题,简单来说就是多加了一个占位符的操作

但是一般我们就是在过滤条件处使用的是占位符,表示不确定性

如图所示:就是好比Statement的写法,无占位符直接进行写定一个数

 PreparedStatement可以更高效的进行批量操作数据,因为它可以进行预编译占位符,之后预编译一次之后我们之后就不用再进行校验,进而实现了批量操作

 PreparedStatement实现对表数据的增删改查的相关代码

 工具类:

package JDBC_Utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class jdbc_Util {
    //建立数据库的连接
    public static Connection getConnection() throws Exception{
        InputStream jdbc_pro = jdbc_Util.class.getClassLoader().getResourceAsStream("JDBC_pro");
        Properties properties = new Properties();
        properties.load(jdbc_pro);
        String user=properties.getProperty("user") ;
        String password=properties.getProperty("password") ;
        String url=properties.getProperty("url") ;
        String driverClass=properties.getProperty("driverClass") ;
        Class.forName(driverClass) ;
        Connection connection= DriverManager.getConnection(user,password,url) ;
        return connection ;
    }
    //关闭连接和Statement的操作
    public static void closeResoure(Connection connection, Statement s) {
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (s!=null) {
            try {
                s.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection connection, Statement s, ResultSet r) {
        try {
            if (connection!=null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
        try {
            if (s!=null) {
                    s.close();
                }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
        try {
            if (r!=null)
                {
                    r.close();
                }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
    }
}

 实现类:

package JDBC;

import JDBC_Utils.jdbc_Util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class PreparedStatementUpdateTest {
    // 向customers表中添加一条记录
    public void testInsert() {
        Connection connection= null;
        PreparedStatement ps= null;
        try {
            //1.加载文件中的四个信息
            InputStream jdbc_pro = ClassLoader.getSystemClassLoader().getResourceAsStream("JDBC_pro");
            //获取文件中的四个信息
            Properties properties = new Properties();
            properties.load(jdbc_pro);
            String user=properties.getProperty("user") ;
            String password=properties.getProperty("password") ;
            String url=properties.getProperty("url") ;
            String driverClass=properties.getProperty("driverClass") ;
            //加载驱动
            Class.forName(driverClass) ;
            //获取连接
            connection = DriverManager.getConnection(driverClass);
            //预编译sql语句,返回PreparedStatement的实例
            String sql
                    ="insert into customers(name,email,birth) values(?,?,?)" ;//?表示占位符
            ps = connection.prepareStatement(sql);
            //填充占位符
            ps.setString(1,"哪吒");
            ps.setString(2,"nezha@gmail.com") ;
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd") ;
            Date date=sdf.parse("1000-01-01") ;
            ps.setDate(3, (java.sql.Date) new Date(date.getTime()));
            //6.执行操作
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //修改customers表的一条记录
    public void testUpdate() throws Exception{
        Connection connection= jdbc_Util.getConnection();
        String sql="update customers set name=? where id = ";
        PreparedStatement ps=connection.prepareStatement(sql);
        ps.setObject(1,"莫扎特");
        ps.setObject(2,18);
        ps.execute();
        jdbc_Util.closeResoure(connection,ps);
    }
    //通用的增删改查操作
    public void update(String sql,Object ...args) throws Exception{
        //sql中占位符的个数与可变形参的长度相同
        //1.获取数据库的连接
        Connection connection=jdbc_Util.getConnection();
        //2.预编译sql语句,返回PreparedStatement的实例
        PreparedStatement ps=connection.prepareStatement(sql) ;
        //3.填充占位符
        for (int i=0;i< args.length;i++) {
            ps.setObject(i+1,args[i]);
        }
        //4.执行
        ps.execute() ;
        //5.资源关闭
        jdbc_Util.closeResoure(connection,ps);
    }
}

 PreparedStatement针对于一个表的查询操作

情况一:属性名和我们表中的列名一模一样

主类:

package JDBC;

import JDBC_Bean.Customer;
import JDBC_Utils.jdbc_Util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;

/**
 *  针对于Customers表的查询操作
 */
public class CustomerForQuery {
    /**
     * 对表查询的通用操作
     * @throws Exception
     */
    public Customer queryForCustomers(String sql,Object...args) {
        Connection connection= null;
        PreparedStatement ps= null;
        ResultSet rs= null;
        Customer cust= null;
        try {
            connection = jdbc_Util.getConnection();
            ps = connection.prepareStatement(sql);
            //填充占位符
            for (int i=0;i< args.length;i++) {
                ps.setObject(i+1,args[i]);
            }
            //返回结果集
            rs = ps.executeQuery();
            //获取结果集中的元数据
            ResultSetMetaData rsmd= rs.getMetaData();
            //通过ResultSetMetaData获取结果集中的列数
            int columnCount=rsmd.getColumnCount() ;
            cust = null;
            if(rs.next()) {
                 cust = new Customer();
                //处理结果集一行数据中的每一个列
                for (int i=0;i<columnCount ;i++) {
                    //获取列值,比如:姓名的值大小,学号的值大小,等等
                    //列的值大小还是位于在结果集当中的,但是对应的列名是位于元数据层面了
                    Object columValue=rs.getObject(i+1) ;
                    //获取每个列的列名,就是姓名或学号等等
                    //String columnName=rsmd.getColumnName(i+1) ;
                    //使用getColumnLabel()方法而不是优先使用getColumnName(i+1)的原因就是:
                    //有可能我们要查询的数据表中的列名和我们JavaBean类中的属性名不相同,所以我们要使用到列的别名
                    //使用getColumnLabel()方法,我们优先返回的是列的别名,如果没有列的别名,那么我们就返回的是列名
                    String columnLabel=rsmd.getColumnLabel(i+1) ;
                    //给cust对象指定的columnLabel属性,赋值为columnValue;
                    // 通过反射我们得到的是属性对象
                    Field field=Customer.class.getDeclaredField(columnLabel);
                    //有可能属性是私有的,所以我们这里使用爆破
                    field.setAccessible(true);
                    //我们这里把cust对象对应的columnLabel属性赋值columValue
                    //这里我们就是利用到了反射,一般我们正常是 对象引用.set(属性对象,要赋给属性的值)
                    //但是我们反射当中是:属性对象.set(对象引用,要给属性的值)
                    field.set(cust,columValue);
                }
            }
            return cust ;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbc_Util.close(connection,ps,rs);
        }
       return null ;
    }
    public void testQuery01() throws Exception{
        Connection connection=jdbc_Util.getConnection();
        String sql="select id,name,email,birth from customers where id = ?" ;
        PreparedStatement ps=connection.prepareStatement(sql);
        //第一个参数表示我们查询第一行位置的操作
        //第二个参数表示我们填充的就是只有一个占位符 也就是表示第一个参数的值,但是是不确定的
        ps.setObject(1,1);
        //执行,返回结果集
        ResultSet resultSet=ps.executeQuery();
        //处理结果集
        if (resultSet.next()) {
            //判断结果集的下一条是否有数据,如果有返回true,并且指针指向下一个

            //获取当前这条数据的各个字段值
            int id=resultSet.getInt(1) ;
            String name=resultSet.getString(2) ;
            String email=resultSet.getString(3) ;
            Date birth=resultSet.getDate(4);
            //把数据封装为一个对象
            Customer customer=new Customer(id,name,email,birth) ;
        }
    }
}

Customer JavaBean包类

package JDBC_Bean;

import java.util.Date;

/**
 * ORM编程思想:
 * 一个数据表对应一个java类
 * 表中的一条记录对应java类的一个对象
 * 表中的一个字段对应java类的一个属性
 */
public class Customer {
    private int id ;
    private String name ;
    private String email ;
    private Date birth ;

    public Customer() {
    }

    public Customer(int id, String name, String email, Date birth) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.birth = birth;
    }

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
}

情况二:属性名和表中的列名存在差异

 

 那么此时我们就要用到列的别名来解决这个问题了,那么我们就要用到:

注意一点就是我们所取的列的别名应该是和属性名是保持一致的

 JavaBean包下的Order类

package JDBC_Bean;

import java.util.Date;

public class Order {
    private int orderId;
    private String orderName;
    private Date orderDate;

    public Order() {
    }

    public Order(int orderId, String orderName, Date orderDate) {
        this.orderId = orderId;
        this.orderName = orderName;
        this.orderDate = orderDate;
    }

    public int getOrderId() {
        return orderId;
    }

    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public Date getOrderDate() {
        return orderDate;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + orderId +
                ", orderName='" + orderName + '\'' +
                ", orderDate=" + orderDate +
                '}';
    }
}

进行查询操作的类:

package JDBC;

import JDBC_Bean.Order;
import JDBC_Utils.jdbc_Util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;

public class OrderForQuery {
    public static void main(String[] args) throws Exception{
        //进行测试
        String sql = "select order_id orderId,order_name orderName,order_date orderDate from order where orderId = ?" ;
        Order order=OrderForQuery(sql,1) ;
        System.out.println(order);
    }
    public static Order OrderForQuery(String sql,Object...args) throws Exception{
        Connection connection=jdbc_Util.getConnection() ;
        PreparedStatement ps=connection.prepareStatement(sql) ;
        //确定占位符
        for (int i=0;i<args.length;i++) {
            ps.setObject(i+1,args[i]);
        }
        ResultSet rs= ps.executeQuery();
        ResultSetMetaData rsd= rs.getMetaData();
        int columnCount= rsd.getColumnCount();
        if(rs.next()) {
            Order order=new Order();
            for (int i=0;i<columnCount;i++) {
                //返回的是列的值,可能为很多类型的
                Object columnValue=rs.getObject(i+1);
                //找出列名,使用getColumnLabel方法,如果有列的别名那么就返回的是列的别名
                //如果无,那么就是返回列名
                String columnLabel =rsd.getColumnLabel(i+1) ;
                //使用反射进行赋值
                Field declaredField = Order.class.getDeclaredField(columnLabel);
                declaredField.setAccessible(true);//进行爆破,为了就是访问私有的属性
                //把这每一个列名对应进行赋值操作
                declaredField.set(order,columnValue);
            }
            return order ;
        }
        return null ;
    }
    public void testQuery1() {
        Connection connection=null ;
        PreparedStatement ps = null ;
        ResultSet rs = null;
        try {
            connection=jdbc_Util.getConnection();
            String sql="select order_id,order_name,order_date from 'order' where order_id = ?" ;
            ps=connection.prepareStatement(sql) ;
            //第一个参数表示我们要查询的就是第一条数据,第二个参数表示填充一个占位符
            ps.setObject(1,1);
            //获取结果集
            rs=ps.executeQuery() ;
            if (rs.next()) {
                int id = (int) rs.getObject(1) ;
                String name = (String) rs.getObject(2) ;
                Date date=(Date) rs.getObject(3) ;
                Order order=new Order(id,name,date) ;
                System.out.println(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbc_Util.close(connection,ps,rs) ;
        }
    }
}

图解—— PreparedStatement查询数据表的流程

 当我们想要在字符串中进行接一个变量时,我们要进行拼串

 

 把双引号进行拼接

 PreparedStatement针对于不同表的查询

package JDBC;

import JDBC_Utils.jdbc_Util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * 实现对不同表的查询
 */
public class PreparedStatementQueryTes {
    //实现对多个表进行查询
    public <T> List<T> getForList(Class<T> clazz,String sql,Object...args) throws Exception{
        Connection connection=jdbc_Util.getConnection();
        PreparedStatement ps=connection.prepareStatement(sql) ;
        for (int i=0;i<args.length;i++) {
            ps.setObject(1,i+1);
        }
        ResultSet rs=ps.executeQuery();
        ResultSetMetaData rsd=rs.getMetaData();
        int columnCount=rsd.getColumnCount();
        ArrayList<T> arrayList=new ArrayList<>();
        while (rs.next()) {
            T t=clazz.newInstance();
            for (int i=0;i<columnCount;i++) {
                Object columnValue = rs.getObject(i + 1);
                String columnLabel=rsd.getColumnLabel(i+1) ;
                Field field = clazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                field.set(t,columnValue);
            }
            arrayList.add(t);
        }
        jdbc_Util.close(connection,ps,rs);
        return arrayList;
    }
    //传过来的第一个参数,实际上就等于 类名.class 。就是一个类对象。如:Class<T> clazz=类名.class
    public <T> T getInstance(Class<T> clazz,String sql,Object...args) throws Exception{
        //1.先建立连接
        Connection connection=jdbc_Util.getConnection();
        //2.获取Prepartment对象
        PreparedStatement ps= connection.prepareStatement(sql);
        //3.给定占位符
        for (int i=0;i< args.length;i++) {
            ps.setObject(1,i+1);
        }
        //4.获取ResultSet对象
        ResultSet rs=ps.executeQuery() ;
        //5.获取元数据对象
        ResultSetMetaData rsd=rs.getMetaData();
        //获取列数
        int columnCount= rsd.getColumnCount();
        if (rs.next()) {
            //6.每一次获得的数据表对应的Class类的实例对象,为之后的反射做准备。
            T t=clazz.newInstance();
            for (int i=0;i<columnCount;i++) {
                //获取列值
                Object columnValue = rs.getObject(i + 1);
                //获取列名
                String columnLabel = rsd.getColumnLabel(i + 1);
                //进行反射得到属性对象
                Field field = clazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                //反射格式和我们的日常格式是截然相反的,平常:实例对象引用.属性
                //反射中是属性对象.实例对象引用,这里set方法类比一下就好了。
                field.set(t,columnValue);
            }
            return t;
        }
        jdbc_Util.close(connection,ps,rs);
        return null ;
    }
}

练习:

1.

package JDBC_test;

import JDBC_Utils.jdbc_Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class test01 {
    public void testInsert() throws Exception{
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String name = scanner.next();
        System.out.print("请输入邮箱:");
        String email = scanner.next();
        System.out.print("请输入生日:");
        String birthday = scanner.next();//'1992-09-08'
        String sql="insert into customers(name,email,birth) values(?,?,?)";
        int insertCount=update(sql,name,email,birthday);
        if(insertCount>0) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    }
    public int update(String sql,Object...args) throws Exception{
        Connection connection=jdbc_Util.getConnection();
        PreparedStatement ps=connection.prepareStatement(sql);
        for(int i=0;i<args.length;i++) {
            ps.setObject(1,args[i]);
        }
        jdbc_Util.closeResoure(connection,ps);
        return ps.executeUpdate();
    }
}

2.

package JDBC_test;

import JDBC_Utils.jdbc_Util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Scanner;

public class test02 {
    /**
     * 问题1:向examstudent表中添加一条记录
     * @throws Exception
     */
    public void insertStuInformation() throws Exception{
        Scanner scanner = new Scanner(System.in);
        System.out.print("四级/六级:");
        int type = scanner.nextInt();
        System.out.print("身份证号:");
        String IDCard = scanner.next();
        System.out.print("准考证号:");
        String examCard = scanner.next();
        System.out.print("学生姓名:");
        String studentName = scanner.next();
        System.out.print("所在城市:");
        String location = scanner.next();
        System.out.print("考试成绩:");
        int grade = scanner.nextInt();
        String sql="insert into examstudent(type,IDCard,examCard,studentName,location,grade) values(?,?,?)";
        int count=update(sql,type,IDCard,examCard,studentName,location,grade);
        if(count>0) {
            System.out.println("信息录入成功");
        } else {
            System.out.println("信息录入失败");
        }
    }
    public int update(String sql,Object...args) {
        Connection connection=null;
        PreparedStatement ps=null;
        try {
            connection=jdbc_Util.getConnection();
            ps=connection.prepareStatement(sql) ;
            for (int i=0;i< args.length;i++) {
                ps.setObject(1,args[i]);
            }
            //执行操作并且执行成功时返回值
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbc_Util.closeResoure(connection,ps);
        }
        return 0;
    }

    /**
     * 问题2:根据身份证号或者准考证号查询学生成绩信息
     * @throws Exception
     */
    public void FindStu() throws Exception{
        System.out.println("请输入您的选择:");
        System.out.println("a:表示选择身份证进行查询学生信息");
        System.out.println("b:表示选择准考证号查询学生信息");
        Scanner scanner = new Scanner(System.in);
        String choice=scanner.next();
        if ("a".equalsIgnoreCase(choice)){
            System.out.println("请输入您的身份证号");
            String IDCard=scanner.next();
            String sql="select type,IDCard,examCard,studentName,location,grade " +
                    "from examstudent where IDCard = ?";
            Student student=find(Student.class,sql,IDCard);
            if (student!=null){
                System.out.println(student);
            } else {
                System.out.println("您的身份证输入有误");
            }
        } else if ("b".equalsIgnoreCase(choice)) {
            System.out.println("请输入您的准考证号");
            String examCard=scanner.next();
            String sql="select type,IDCard,examCard,studentName,location,grade from " +
                    "examstudent where examCard = ? ";
            Student student=find(Student.class,sql,examCard);
            if (student!=null){
                System.out.println(student);
            } else {
                System.out.println("您的准考证号输入有误");
            }
        } else {
            System.out.println("您的输入有误");
        }
    }
    public <T> T find(Class<T> clazz,String sql,Object...args) throws Exception{
        Connection connection=jdbc_Util.getConnection();
        PreparedStatement ps=connection.prepareStatement(sql);
        for (int i=0;i< args.length;i++) {
            ps.setObject(1,args[i]);
        }
        ResultSet rs= ps.getResultSet();
        ResultSetMetaData rsd= rs.getMetaData();
        int columnCount= rsd.getColumnCount();
        if (rs.next()) {
            T t=clazz.newInstance();
            for (int i = 0;i<columnCount;i++) {
                Object columnValue=rs.getObject(i+1) ;
                String columnLabel=rsd.getColumnLabel(i+1) ;
                Field field=clazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                field.set(t,columnValue);
            }
            return t;
        }
        return null;
    }
    /**
     * 问题3:删除指定的学生信息
     */
    public void deleteStuInformation() throws Exception{
        while (true) {
            System.out.println("请输入学生的考号");
            Scanner scanner = new Scanner(System.in);
            String examCard=scanner.next();
            String sql="select examCard from examstudent where examCard = ?" ;
            int update = update(sql, 1);
            if (update>0) {
                String sql2="delete from examstudent where examCard = ?";
                int update1 = update(sql2, 2);
                if (update1>0) {
                    System.out.println("删除成功");
                    break;
                } else {
                    System.out.println("删除失败");
                }
            } else {
                System.out.println("输入错误");
            }
        }
    }
    //优化
    public void WelltestDelete() {
        while (true) {
            System.out.println("请输入学生的考号");
            Scanner scanner = new Scanner(System.in);
            String examCard = scanner.next();
            String sql = "delete from examstudent where examCard = ?";
            int deleteCount = update(sql, 2);
            if (deleteCount > 0) {
                System.out.println("删除成功");
                break;
            } else {
                System.out.println("删除失败,请重新输入");
            }
        }
    }
}

如何查看表数据的类型?

添加一张图片,以流的形式 

 向数据表中插入和查询Blob类型的字段

package JDBC;

import JDBC_Bean.Customer;
import JDBC_Utils.jdbc_Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;

public class BlobTest {
    /**
     * 插入Blob类型的字段
     * @throws Exception
     */
        public void testInsert() throws Exception {
        Connection connection=jdbc_Util.getConnection();
        String sql="Insert into customers(name,email,birth,photo) values(?,?,?,?)";
        PreparedStatement ps=connection.prepareStatement(sql);

        ps.setObject(1,"袁浩");
        ps.setObject(2, "yuan@qq.com");
        ps.setObject(3,"1992-09-08");
        FileInputStream is = new FileInputStream(new File("girl.jpg"));
        ps.setBlob(4, is);
        ps.execute();
       jdbc_Util.closeResoure(connection,ps);
    }
    /**
     * 查询数据表customers中Blob类型的字段
     */
    public void Find() throws Exception{
        Connection connection=jdbc_Util.getConnection();
        String sql="select id,name,email,birth,photo from customers where id = ? " ;
        PreparedStatement ps=connection.prepareStatement(sql);
        ps.setInt(1,2);
        ResultSet rs= ps.getResultSet();
        if (rs.next()) {
            int id=rs.getInt("id");
            String name=rs.getString("name");
            String email=rs.getString("email");
            Date birth=rs.getDate("birth");
            Customer customer = new Customer(id,name, email, birth);
            //将Blob类型的字段下载下来,以文件的方式保存到本地
            Blob photo=rs.getBlob("photo");
            InputStream binaryStream = photo.getBinaryStream();
            FileOutputStream fileOutputStream = new FileOutputStream("xxx.jpg");
            byte[] buffer=new byte[1024];
            int len ;
            while ((len=binaryStream.read(buffer))!=-1) {
                fileOutputStream.write(buffer,0,len);
            }
        }
    }
}

使用PreparedStatement实现批量数据的操作

为了实现批量操作,我们要使用1.37的jar包,

1.先删除1.7的jar包

 

 2.再把1.7版本的jar包添加到Bath即可

 

package JDBC;

import JDBC_Utils.jdbc_Util;

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

public class InsertTest {
    //批量插入的方式二
    public void testInsert1() {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //获取起始时间
            long start = System.currentTimeMillis();
            //获取连接
            connection = jdbc_Util.getConnection();
            //搞出sql语句
            String sql =
                    "insert into goods(name) values(?)";
            ps = connection.prepareStatement(sql);
            for (int i = 0; i <= 20000; i++) {
                ps.setObject(1, "name_" + i);
                ps.execute();
            }
            long end = System.currentTimeMillis();
            System.out.println("所花费的时间为:" + (end - start));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbc_Util.closeResoure(connection, ps);
        }
    }
        /*
         * 批量插入的方式三:
         * 1.addBatch()、executeBatch()、clearBatch()
         * 2.mysql服务器默认是关闭批处理的,我们需要通过一个参数,让mysql开启批处理的支持。
         * 		 ?rewriteBatchedStatements=true 写在配置文件的url后面
         * 3.使用更新的mysql 驱动:mysql-connector-java-5.1.37-bin.jar
         */
        public void testInsert03 () throws Exception {
            long start = System.currentTimeMillis();
            Connection connection = jdbc_Util.getConnection();
            String sql = "insert into goods(name) values(?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            for (int i = 0; i < 1000000; i++) {
                ps.setObject(1, "name_" + i);
                //1.攒sql
                ps.addBatch();
                if (i % 500 == 0) {
                    //2.执行Batch
                    ps.executeBatch();
                    //3.清空Batch
                    ps.clearBatch();
                }
            }
            jdbc_Util.closeResoure(connection, ps);
        }
    //批量插入的方式四:设置连接不允许自动提交数据
    public void test04() throws Exception{
            long start = System.currentTimeMillis();
            Connection connection=jdbc_Util.getConnection();
            //设置不允许自动提交数据
        connection.setAutoCommit(false);
        String sql ="insert into goods(name) values(?)" ;
        PreparedStatement ps= connection.prepareStatement(sql);
        for (int i =0;i<100000;i++) {
            ps.setObject(1,"name_"+i);
            ps.addBatch();
            if (i%500==0) {
                ps.executeBatch();
                ps.clearBatch();
            }
        }
        //提交
        connection.commit();
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        jdbc_Util.closeResoure(connection,ps);
        }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值