首页 > 编程知识 正文

并循环写入mysql数据库(mysql数据库写入数据)

时间:2023-12-20 16:55:06 阅读:318532 作者:RYUC

本文目录一览:

MySQL数据库 写入大量数据如何实现

//最快的方法 10000记录 23MS

public static void insert() {  

        // 开时时间  

        Long begin = new Date().getTime();  

        // sql前缀  

        String prefix = "INSERT INTO tb_big_data (count, create_time, random) VALUES ";  

        try {  

            // 保存sql后缀  

            StringBuffer suffix = new StringBuffer();  

            // 设置事务为非自动提交  

            conn.setAutoCommit(false);  

            // Statement st = conn.createStatement();  

            // 比起st,pst会更好些  

            PreparedStatement pst = conn.prepareStatement("");  

            // 外层循环,总提交事务次数  

            for (int i = 1; i = 100; i++) {  

                // 第次提交步长  

                for (int j = 1; j = 10000; j++) {  

                    // 构建sql后缀  

                    suffix.append("(" + j * i + ", SYSDATE(), " + i * j  

                            * Math.random() + "),");  

                }  

                // 构建完整sql  

                String sql = prefix + suffix.substring(0, suffix.length() - 1);  

                // 添加执行sql  

                pst.addBatch(sql);  

                // 执行操作  

                pst.executeBatch();  

                // 提交事务  

                conn.commit();  

                // 清空上一次添加的数据  

                suffix = new StringBuffer();  

            }  

            // 头等连接  

            pst.close();  

            conn.close();  

        } catch (SQLException e) {  

            e.printStackTrace();  

        }  

        // 结束时间  

        Long end = new Date().getTime();  

        // 耗时  

        System.out.println("cast : " + (end - begin) / 1000 + " ms");  

    }

怎么通过循环的方式向mysql数据库中插入数据

你是要一次插入多条数据么,如果是的话,你可以拼装sql语句,一条语句执行,这样会快很多

insert

into(...)

(

(select

...from

dual)

union

all

(select

..

from

dual)

.

mysql 怎么循环插入多条数据

一条insert语句批量插入多条记录

常见的insert语句,向数据库中,一条语句只能插入一条数据:

insert into persons

(id_p, lastname , firstName, city )

values(204,'haha' , 'deng' , 'shenzhen');

(如上,仅插入了一条记录)

怎样一次insert插入多条记录呢?

示例:

insert into persons

(id_p, lastname , firstName, city )

values

(200,'haha' , 'deng' , 'shenzhen'),

(201,'haha2' , 'deng' , 'GD'),

(202,'haha3' , 'deng' , 'Beijing');

这样就批量插入数据了, 遵循这样的语法,就可以批量插入数据了。

执行成功

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。