2016-04-29 13 views
2

jdbcを使用してレコードIデータベーステーブルを一定の間隔で追加したいとします。Javaで一定の時間間隔で多くのデータを追加します。

たとえば、100000レコードを10秒間隔で追加したいので、10000 /秒を挿入します。

として以下のMySQLの私のコード:、あなたが効果的にデータベース・ラウンドトリップを削減するバッチクエリを使用して

String url1 = "jdbc:mysql://localhost:3306/xyz"; 
String user = "root"; 
String password = "root"; 
conn1 = DriverManager.getConnection(url1, user, password); 
if (conn1 != null) { 
    System.out.println("Connected to the database xyz"); 
    for(int i=0;i<=n;i++){ // where n is no. of record that I want to insert 
     // Here is my insert logic 
    } 
} 
+3

のようなものを意味しその後の質問は、実際には何ですか? –

+0

私はデータベースに挿入する必要がある多くのデータを持っていますが、ある時間間隔でそれらのデータを追加したいという条件があります。 たとえば、100000のデータがあり、10秒間にこれらのデータを追加したい場合は、100000/10 = 10000データ/秒のデータが追加されます。 –

+0

@yogeshjalodaraなぜそれを制限したいのかわからないが、Thread.sleep(長いミリ秒)。あなたが探している方法です.. – user2494817

答えて

3

を私はその

final long loopDuration = 1;//second 
final long totalSize = 100000; 
final long timeInterval = 10; 
final AtomicLong batchNumber = new AtomicLong((long)Math.ceil((double) timeInterval/loopDuration)); 
Timer timer = new Timer(); 
timer.schedule(new TimerTask() { 
    @Override 
    public void run() { 
     //insert logic 
     if (batchNumber.decrementAndGet() == 0) { 
      timer.cancel(); 
      timer.purge(); 
     } 

    } 
}, 0, loopDuration * 1000); 
2

が、あなたはJavaアプリケーションのパフォーマンスが向上し、ネットワークの待ち時間、に費やす時間を大幅に節約。

public class MySQLJdbcExample { 

    public static void main(String args[]) throws SQLException { 

     String url="jdbc:mysql://localhost:3306/test"; 
     Connection conn = DriverManager.getConnection(url, "root", "root"); 
     String query = "insert into employee values (?,?,NULL)"; 
     PreparedStatement pStatement = conn.prepareStatement(query); 
     int batchSize = 100; 

     long startTime = System.currentTimeMillis(); 
     for (int count = 0; count < 1000; count++) { 
      pStatement.setString(1, Integer.toString(count)); 
      pStatement.setString(2, "Employee" + count); 
      pStatement.addBatch(); 

      if (count % batchSize == 0) { 
       pStatement.executeBatch(); 
      } 
     } 

     pStatement.executeBatch() ; //for remaining batch queries if total record is odd no. 

    // conn.commit(); 
     pStatement.close(); 
     conn.close(); 
     long endTime = System.currentTimeMillis(); 
     long elapsedTime = (endTime - startTime)/1000; //in seconds 
     System.out.println("Total time required to execute 1000 queries using PreparedStatement with JDBC batch insert is :" + elapsedTime); 



    } 
} 

続きを読む:私のコメントでヨーゲッシュ-jalodara @http://javarevisited.blogspot.com/2013/01/jdbc-batch-insert-and-update-example-java-prepared-statement.html#ixzz47Bgqyx64

関連する問題