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)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 临朐县| 玉田县| 吉林省| 都江堰市| 新源县| 广东省| 沧州市| 贵州省| 顺义区| 内丘县| 余江县| 定南县| 静安区| 诸暨市| 新河县| 酒泉市| 隆子县| 剑阁县| 荣成市| 巧家县| 辉县市| 五原县| 都兰县| 上犹县| 潼关县| 文登市| 和田县| 新蔡县| 安图县| 乐陵市| 博湖县| 伊金霍洛旗| 星座| 新巴尔虎右旗| 鄯善县| 黄骅市| 洪洞县| 涿州市| 朔州市| 清水河县| 东台市|