qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          3分鐘如何向MySQL數據庫中插入100萬條數據

            一、編寫測試案例向MySQL數據庫中插入百萬條數據。測試數據表建表腳本如下:use db_xk;

          drop table if exists tb_test2;
          create table tb_test2 (
          id int primary key auto_increment,
          subject varchar(50) not null,
          description varchar(200) not null,
          teacher_id int(10) zerofill not null,
          student_id int(10) zerofill default null,
          state boolean not null default false
          );state boolean not null default false
          );

            測試案例源碼如下:

          package test;
          import java.sql.Connection;
          import java.sql.PreparedStatement;
          import java.sql.SQLException;
          import util.DBUtil;
          public class TestDataBase2 {
          public static void main(String[] args) {
          Connection conn = DBUtil.getConnection();
          String sql = "insert into tb_test2(subject, description, teacher_id, student_id) values (?,?,?,?)";
          try {
          PreparedStatement prep = conn.prepareStatement(sql);
          // 將連接的自動提交關閉,數據在傳送到數據庫的過程中相當耗時
          conn.setAutoCommit(false);
          long start = System.currentTimeMillis();
          for (int i = 0; i < 10; i++) {
          long start2 = System.currentTimeMillis();
          // 一次性執行插入10萬條數據
          for (int j = 0; j < 100000; j++) {
          prep.setString(1, "test2");
          prep.setString(2, "test3");
          prep.setInt(3, 1234562);
          prep.setInt(4, 12354545);
          // 將預處理添加到批中
          prep.addBatch();
          }
          // 預處理批量執行
          prep.executeBatch();
          prep.clearBatch();
          conn.commit();
          long end2 = System.currentTimeMillis();
          // 批量執行一次批量打印執行依次的時間
          System.out.print("inner"+i+": ");
          System.out.println(end2 - start2);
          }
          long end = System.currentTimeMillis();
          System.out.print("total: ");
          System.out.println(end - start);
          } catch (SQLException e) {
          e.printStackTrace();
          } finally {
          DBUtil.close(conn);
          }
          }
          }

          posted on 2013-09-02 10:26 順其自然EVO 閱讀(3712) 評論(0)  編輯  收藏 所屬分類: 數據庫

          <2013年9月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 靖远县| 皋兰县| 南涧| 金堂县| 澄江县| 溧水县| 龙里县| 宣武区| 宝清县| 东兴市| 垦利县| 峨眉山市| 乌兰县| 新沂市| 资兴市| 汕头市| 永城市| 靖安县| 包头市| 卓尼县| 临颍县| 镇江市| 达日县| 凤山县| 临汾市| 中卫市| 会昌县| 玛多县| 嫩江县| 渝中区| 台安县| 双流县| 宜兰市| 大丰市| 龙山县| 嵩明县| 策勒县| 庆阳市| 东城区| 梅河口市| 闽清县|