1

私は、eclipse、eclipseLink、java persistence API(JPA)、および同じ構造(同じテーブル)を持つ2つのデータベース(MYSQLとSQLServer)を使用してJavaプロジェクトで作業しています。「if」などの条件ステートメントを適用するために使用しているデータベースを確認する必要がある場合があります。問題は、MySQLまたはSQLServerデータベースに接続しているかどうかを確認し、その情報をパラメーターで使用するにはどうすればよいですか?

4

2 に答える 2

0

ブール値connectedToDatabaseを作成し、falseに初期化します。接続を確立するtryandcatchブロックを作成します。内で、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");

サーバーがダウンした場合、これは機能しません。これは、最初の接続が成功したかどうかのみを判別するためです。

于 2012-05-07T20:55:11.547 に答える
0

私は、persistence.xml構成ファイルでタグプロパティ属性 name="eclipselink.target-database"を読み取る問題を解決しました。私はこれらのインポートを使用しました:

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;

そして、これは私がプロパティを読み取るために使用した関数です:

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」などの条件ステートメントで使用できます。

于 2012-05-15T16:47:41.617 に答える