简体   繁体   中英

Verifying the database which is connected - Java persistence API

I'm working in a java project using eclipse, eclipseLink, java persistence API (JPA) and two databases (MYSQL and SQLServer) with the same structure (same tables). Sometimes I need to check the database that I'm using to apply conditional statements such as “if” or others. The question is: How can i verify if I'm connected to a MySQL or SQLServer database using and use that information in a parameter?

create a boolean value connectedToDatabase and initialize it to false. create a try and catch block that will make the connection. within try initialize connectedToDatabase to true. If an exception is caught when trying to connect the boolean value will remain false.

private boolean connectedToDatabase = false;

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

then you can make an if statement that will throw an exception if connectedToDatabase is false. just make sure the method throws IllegalStateException.

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

This wouldn't work if the server went down, because it will only determine if the initial connection was successful.

I solved the problem reading the tag property and the Attribute name="eclipselink.target-database" at the persistence.xml configuration file. I used these imports:

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;

And this is the function that I used to read the property:

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;
}

In another class you should to assign to a String the return of this method. And that's the answer, now you can use this information in a conditional statement like "if".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM