2016-06-21 3 views
1

私のアプリケーションは、このコードを使用して取得されたMySQLの接続、使用しています:MySQLデータベースサーバが実行されていないので、私のアプリは、接続を開くことができない場合Javaは、MySQLの接続を待っている

public static void Connect(){ 
    try 
    { 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     String url = "jdbc:mysql://" + host + ":" + port + "/"+ db; 
     ct = DriverManager.getConnection(url, user, pass); 
     st = ct.createStatement(); 
     System.out.println("Csatlakozva....\n"); 
    } 
    catch (InstantiationException e) 
    { 
     Main.textArea.setText("Error : Instantiation!"); 
     //System.err.println("Error : Instantiation"); 
     e.printStackTrace(); 
    } 
    catch (IllegalAccessException e) 
    { 
     Main.textArea.setText("Error : Illegális Behatolás!"); 
     //System.err.println("Error : Illegális Behatolás!"); 
     e.printStackTrace(); 
    } 
    catch (ClassNotFoundException e) 
    { 
     Main.textArea.setText("Error : Class Nem Található!"); 
     //System.err.println("Error : Class Nem Található!"); 
     e.printStackTrace(); 
    } 
    catch (SQLException e) 
    { 
     Main.textArea.setText("Error : Adatbázis Nem Található!"); 
     //System.err.println("Error : Adatbázis Nem Található!"); 
     e.printStackTrace(); 
    } 
} 

を、私はどのように作るのですが私のアプリは接続が確立されるまで待つ?

+0

コードにコメントを追加して、待機時間を表示できますか?これはローカルまたはリモートのMySQLインスタンスですか?どのような手術システムを使用していますか? –

+0

ここにあなたの正確な質問は何ですか?あなたは何をしたいですか? –

+0

@Michael Markidis私のやりたいことは...接続コードがあります...私のアプリケーションが接続を開くことができないようにmysqlが実行されていない場合、私のアプリは接続が何かをするのを待つ必要があります。 –

答えて

1

にJDBC接続コードを置くことができます。このようなもの:

public static void Connect() throws InterruptedException { // It isn't nice to block forever, so we will allow for interrupt 
    for (;;) { 
     try 
     { 
      Class.forName("com.mysql.jdbc.Driver").newInstance(); 
      String url = "jdbc:mysql://" + host + ":" + port + "/"+ db; 
      ct = DriverManager.getConnection(url, user, pass); 
      st = ct.createStatement(); 
      System.out.println("Csatlakozva....\n"); 
      return; // Break out of loop because we got a connection - no exception was thrown 
     } ... 

     // One of the exceptions happened. We will continue to loop so 
     // we try to connect again until we are successful. We don't want 
     // to retry too fast, because painful experience has taught us that 
     // bad things can happen (full logs, 100% CPU, etc.). 
     Thread.sleep(1); 
    } 
} 

このような低レベルの問題を調査して理解することは有効です。ただし、ほとんどのアプリケーションでデータベース接続を管理するために接続プールが使用されていることに注意してください。一般に、接続プールは、接続が得られるまで(通常は限定された時間)ブロック機能を提供します。つまり、接続プールは以前に作成された接続の再利用を可能にするだけでなく、必要に応じて接続の再試行も処理します。

+0

ありがとうございます!それは私のためにうまく動作します:) –

0

スレッドの問題があると思います。

はあなたのConnect方法は、接続が実際に得られるまで、あなたがループして、既存のtryブロックを囲む必要が戻らないようにするために、新しいスレッド

private class JDBCConnection extends Thread{ 

public void run(){ 
.... 
} 

} 
関連する問題