批量插入数据库

来源:互联网 发布:php技术 编辑:程序博客网 时间:2024/06/04 17:45
package bean;/* * 批量插入数据库 */import java.sql.Connection;import java.sql.Date;import java.sql.DriverManager;import java.text.SimpleDateFormat;import java.util.Random;import java.util.TimeZone;import com.mysql.jdbc.PreparedStatement;public class fwfwefwe {public static void main(String[] args) throws Exception  {        Class.forName("com.mysql.jdbc.Driver");        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/aaa", "root", "0000");        // 关闭事务自动提交        con.setAutoCommit(false);                        //计算运行时间        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS");        TimeZone t = sdf.getTimeZone();        t.setRawOffset(0);        sdf.setTimeZone(t);        Long startTime = System.currentTimeMillis();                PreparedStatement pst = (PreparedStatement) con.prepareStatement("insert into text001 values (?,?,null,null)");                        //插入像 01 02 03 04 05 06 07 08 09 10 这样的数字for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {//随机生成随机数int max=666;        int min=0;        Random random = new Random();        int s = random.nextInt(max)%(max-min+1) + min;String AA = i + "" + j;System.out.println(AA);            pst.setString(1, AA);                        //插入随机生成的数据            pst.setInt(2, s);            // 把一个SQL命令加入命令列表            pst.addBatch();}}        // 执行批量更新        pst.executeBatch();        // 语句执行完毕,提交本事务        con.commit();        Long endTime = System.currentTimeMillis();        System.out.println("用时:" + sdf.format(new Date(endTime - startTime)));        pst.close();        con.close();}}
原创粉丝点击