PreparedStatement 简单操作数据库

PreparedStatementTest操作数据库

配置文件:JDBCUtilsjdbc.properties:注意在jdbc.properties的url中配置批处理开启,下面有讲解,如果不开启方式二和方式一的结果一样;

1.test()  :插入数据

2.test1():插入含有blob类型数据

如果字段属性设置为:mediumblob,则在MySQL的my.ini文件中设置:max_allowed_packet=16M(在末尾添加),完成后重新启动mysql服务

3.test2():查询数据表中插入blob数据类型

4.test3():PreperdStatement批量操作方式一(插入一万条数据)

* for 循环

5.test4():PreperdStatement批量操作方式二(比方式一更快)

* 1.addBatch() 2.executeBatch() 3.clearBatch()
* 2.mysql服务器默认是关闭批处理的,我问需要通过一个参数让mysql开启批处理支持
*       rewriteBatchedStatements=true 写在配置文件(jdbc.properties)的url后面

6.test():PreperdStatement批量操作:设置连接不允许自动提交数据(终极版)(插入一百万条数据)

 BLOB类型

package JDBCPreparedStatement;

import JDBCUtil.JDBCUtils;
import org.junit.Test;

import java.io.*;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * @Author HLY
 * @Create 2019-12-05 11:39
 */
public class PreperdStatementUpdateTest {

    /*
    * 使用PreperdStatement替换Statement,实现对数据表的增删改查操作
    *
    * 1.使用PreperdStatement操作Blob的数据,而Statement做不到
    *
    * 2.使用PreperdStatement可以实现更高效的批量操作
    *
    * */

    //添加
    @Test
    public void test() throws IOException, ClassNotFoundException, SQLException, ParseException  {

        Connection connection= JDBCUtils.getConnection();
        //预编译sql语句
        String sql="insert into user(name,birth,email) values(?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //填充占位符
        preparedStatement.setString(1,"郭军");
        preparedStatement.setString(3,"[email protected]");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date=simpleDateFormat.parse("1994-12-16");
        preparedStatement.setDate(2, new java.sql.Date(date.getTime()));
        //执行操作
        preparedStatement.execute();

        JDBCUtils.closeResource(connection,preparedStatement,null);

    }

    //像数据表中插入blob数据类型
    @Test
    public void test1() throws SQLException, IOException, ClassNotFoundException, ParseException {

        Connection connection= JDBCUtils.getConnection();
        //预编译sql语句
        String sql="insert into user(name,birth,email,photo) values(?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //填充占位符
        preparedStatement.setString(1,"郭军");
        preparedStatement.setString(3,"[email protected]");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date=simpleDateFormat.parse("1994-12-16");
        preparedStatement.setDate(2, new java.sql.Date(date.getTime()));

        FileInputStream inputStream=new FileInputStream(new File("D:\\图片\\2.jpg"));

        preparedStatement.setBlob(4,inputStream);
        //执行操作
        preparedStatement.execute();

        JDBCUtils.closeResource(connection,preparedStatement,null);

    }

    //查询数据表中插入blob数据类型
    @Test
    public void test2() throws SQLException, IOException, ClassNotFoundException, ParseException {

        Connection connection= null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        InputStream inputStream=null;
        FileOutputStream fileOutputStream=null;
        try {
            connection = JDBCUtils.getConnection();
            //预编译sql语句
            String sql="select * from user where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,6);
            //执行操作获取结果集
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                //方式一
               /* int id=resultSet.getInt(1);
                String name =resultSet.getString(2);
                Date birth =resultSet.getDate(3);
                String email=resultSet.getString(4);*/
                //方式二
                int id=resultSet.getInt("id");
                String name =resultSet.getString("name");
                Date birth =resultSet.getDate("birth");
                String email=resultSet.getString("email");

                User user=new User(id,name,birth,email);
                System.out.println(user.toString());

                //将Blob类型字段保存到本地
                Blob photo=resultSet.getBlob("photo");
                inputStream=photo.getBinaryStream();
                fileOutputStream=new FileOutputStream("guojun.jpg");
                byte[] bytes=new byte[1024];
                int len;
                while ((len=inputStream.read(bytes))!=-1){
                    fileOutputStream.write(bytes,0,len);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (inputStream!=null){
                inputStream.close();
            }
            if (fileOutputStream!=null){
                fileOutputStream.close();
            }
        }
        JDBCUtils.closeResource(connection,preparedStatement,resultSet);
    }

    //PreperdStatement批量操作方式一:
    @Test
    public void test3() throws SQLException, IOException, ClassNotFoundException, ParseException {

        Connection connection= null;
        PreparedStatement preparedStatement = null;
        try {
            long start=System.currentTimeMillis();
            connection = JDBCUtils.getConnection();
            String sql ="INSERT INTO user(name,birth,email)VALUES(?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            for (int i=1;i<=10000;i++){
                preparedStatement.setString(1,"郭军");
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                Date date=simpleDateFormat.parse("1994-12-16");
                preparedStatement.setDate(2,new java.sql.Date(date.getTime()));
                preparedStatement.setString(3,"[email protected]");

                preparedStatement.execute();
            }
            long end=System.currentTimeMillis();
            System.out.println("时间:"+(end-start));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,preparedStatement,null);
    }



    //PreperdStatement批量操作
    /*
    * 1.addBatch() 2.executeBatch() 3.clearBatch()
    * 2.mysql服务器默认是关闭批处理的,我问需要通过一个参数让mysql开启批处理支持
    *       rewriteBatchedStatements=true 写在配置文件(jdbc.properties)的url后面
    * 3.
    * */
    @Test
    public void test4() throws SQLException{

        Connection connection= null;
        PreparedStatement preparedStatement = null;
        try {
            long start=System.currentTimeMillis();
            connection = JDBCUtils.getConnection();
            String sql ="INSERT INTO user(name,birth,email)VALUES(?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            for (int i=1;i<=10000;i++){
                preparedStatement.setString(1,"郭军");
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                Date date=simpleDateFormat.parse("1994-12-16");
                preparedStatement.setDate(2,new java.sql.Date(date.getTime()));
                preparedStatement.setString(3,"[email protected]");
                //1.保存sql
                preparedStatement.addBatch();
                if (i%500==0){
                    //2.执行
                    preparedStatement.executeBatch();
                    //3.清空batch
                    preparedStatement.clearBatch();
                }
            }
            long end=System.currentTimeMillis();
            System.out.println("时间:"+(end-start));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,preparedStatement,null);
    }

    //PreperdStatement批量操作:设置连接不允许自动提交数据
    @Test
    public void test5() throws SQLException{

        Connection connection= null;
        PreparedStatement preparedStatement = null;
        try {
            long start=System.currentTimeMillis();
            connection = JDBCUtils.getConnection();
            //设置不允许自动提交数据
            connection.setAutoCommit(false);
            String sql ="INSERT INTO user(name,birth,email)VALUES(?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            for (int i=1;i<=10000;i++){
                preparedStatement.setString(1,"郭军");
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                Date date=simpleDateFormat.parse("1994-12-16");
                preparedStatement.setDate(2,new java.sql.Date(date.getTime()));
                preparedStatement.setString(3,"[email protected]");
                //1.保存sql
                preparedStatement.addBatch();
                if (i%500==0){
                    //2.执行
                    preparedStatement.executeBatch();
                    //3.清空batch
                    preparedStatement.clearBatch();
                }
            }
            //提交数据
            connection.commit();
            long end=System.currentTimeMillis();
            System.out.println("时间:"+(end-start));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,preparedStatement,null);
    }

}

User对象: 

package JDBCPreparedStatement;

import java.util.Date;

/**
 * @Author HLY
 * @Create 2019-12-17 16:58
 */
public class User {

    public int id;
    public String name ;
    public Date birth ;
    public String email;

    public User(){}

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


    public void setId(int id){
        this.id=id;
    }
    public int getId(){
        return this.id;
    }

    public void setname(String name){
        this.name=name;
    }
    public String getname(){
        return this.name;
    }

    public void setemail(String email){
        this.email=email;
    }
    public String getemail(){
        return this.email;
    }

    public void setbirth(Date birth){
        this.birth=birth;
    }
    public Date getbirth(){
        return this.birth;
    }

    @Override
    public String toString() {
        return "User{id="+id+",name="+
                name+",birth="+
                birth+",email="+email+"}";
    }
}

猜你喜欢

转载自blog.csdn.net/paroleg/article/details/103597410