教你如何6秒钟往MySQL插入100万条数据
一、思路
往MySQL中插入1000000条数据只花了6秒钟!
关键点:
1。使用PreparedStatement对象
2。rewriteBatchedStatementstrue开启批量插入,插入只执行一次,所有插入比较快。
二、代码packagetest0823。demo1;importjava。sql。;author:BeiZhendate:202008240:43publicclassJDBC2{staticintcount0;publicstaticvoidmain(String〔〕args){longstartSystem。currentTimeMillis();conn();longendSystem。currentTimeMillis();System。out。println(耗时:(endstart)1000秒);}publicstaticvoidconn(){1。导入驱动jar包2。注册驱动(mysql5之后的驱动jar包可以省略注册驱动的步骤)Class。forName(com。mysql。jdbc。Driver);3。获取数据库连接对象Connectionconnnull;PreparedStatementpstmtnull;{try{rewriteBatchedStatementstrue,一次插入多条数据,只插入一次connDriverManager。getConnection(jdbc:mysql:test?rewriteBatchedStatementstrue,root,root);4。定义sql语句Stringsqlinsertintouservalues(default,?,?);5。获取执行sql的对象PreparedStatementpstmtconn。prepareStatement(sql);6。不断产生sqlfor(inti0;i1000000;i){pstmt。setString(1,(int)(Math。random()1000000));pstmt。setString(2,(int)(Math。random()1000000));pstmt。addBatch();}7。往数据库插入一次数据pstmt。executeBatch();System。out。println(添加1000000条信息成功!);}catch(SQLExceptione){e。printStackTrace();}finally{8。释放资源避免空指针异常if(pstmt!null){try{pstmt。close();}catch(SQLExceptione){e。printStackTrace();}}if(conn!null){try{conn。close();}catch(SQLExceptione){e。printStackTrace();}}}}}}三、运行结果添加1000000条信息成功!耗时:6秒