2012-05-07 27 views
1

私は、eclipse、eclipseLink、Java永続性API(JPA)と同じ構造(同じテーブル)を持つ2つのデータベース(MYSQLとSQLServer)を使用してJavaプロジェクトで作業しています。時には、 "if"などの条件文を適用するために使用しているデータベースをチェックする必要があります。質問は次のとおりです: MySQLまたはSQLServerデータベースに接続してその情報をパラメータで使用しているかどうかを確認するにはどうすればよいですか?接続されているデータベースの確認 - Java永続性API

答えて

0

私はpersistence.xmlの設定ファイルにタグ財産属性名=「eclipselink.target-データベース」を読んで問題を解決しました。私はこれらの輸入品使用:

import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.DocumentBuilder; 
import org.w3c.dom.Document; 
import org.w3c.dom.NodeList; 
import org.w3c.dom.Node; 
import org.w3c.dom.Element; 

をそして、これは私がプロパティを読み取るために使用する関数です:Stringに、このメソッドの戻り値を割り当てるために、あなたがしなければならない別のクラスで

public String DatabaseIdentifier() 
{ 
    String dbIdentifier=null ; 
    try { 
     //Creates a virtual file where is allowed for default the persistence.xml configurarion file 
     File path= new File("src\\META-INF"); 

     //Using the xml libraries prepare the document to be read. 
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = dBuilder.parse(new File(path+"\\persistence.xml")); 
     doc.getDocumentElement().normalize(); 

     //Gets the list of properties contained in the persistence.xml file 
     NodeList listProperties= doc.getElementsByTagName("property"); 

     //We searching in the list of properties the attribute with the name 
     //eclipselink.target-database and there we get the database that 
     //is in use. 
     for (int i = 0; i < listProperties.getLength(); i ++) { 
      Node team = listProperties.item(i); 

      if (team.getNodeType() == Node.ELEMENT_NODE)  
      { 
       Element element = (Element) team; 

      if (element.getAttribute("name").contains("eclipselink.target-database")) 
        { 
       dbIdentifier=element.getAttribute("value").toString(); 
       System.out.println(element.getAttribute("value")); 
        } 

      } 
     } 
    } catch (Exception e) 
    {e.printStackTrace();} 
    return dbIdentifier; 
} 

。それが答えです。今では、 "if"のような条件文でこの情報を使用できます。

0

boolean値connectedToDatabaseを作成し、falseに初期化します。 接続を確立するtryとcatchブロックを作成します。 try内でconnectedToDatabaseをtrueに初期化します。ブール値に接続しようとしたときに例外がキャッチされた場合はfalseのままです。

private boolean connectedToDatabase = false; 

try 
{ 
    connection = DriverManager.getConnection(urlOfDatabase); 
    connectedToDatabase = true; 
}catch(SQLException sqlException){ 
    sqlException.printStackTrace();} 

次に、connectedToDatabaseがfalseの場合に例外をスローするif文を作成できます。メソッドがIllegalStateExceptionをスローすることを確認してください。

if(!connectedToDatabase) 
    throw new IllegalStateException("Not Connected To Database"); 

初期接続が成功したかどうかを判断するだけなので、サーバーがダウンした場合、これは機能しません。

+0

JAVAで従来のデータベース接続に使用されていたコードを投稿したため、これは答えではありません。これは、JPAとpersistence.xmlファイルを使用するプロジェクトでは機能しません。 – dpetersen

関連する問題