验证连接的数据库 - Java持久性API

时间:2012-05-07 19:58:04

标签: java mysql sql-server eclipse eclipselink

我正在使用eclipse,eclipseLink,java持久性API(JPA)和两个具有相同结构(相同表格)的数据库(MYSQL和SQLServer)的java项目中工作。有时我需要检查我用来应用条件语句的数据库,例如“if”或其他。问题是: 如何在参数中使用和使用该信息来验证我是否连接到MySQL或SQLServer数据库?

2 个答案:

答案 0 :(得分:0)

创建一个布尔值connectedToDatabase并将其初始化为false。 创建一个try和catch块来进行连接。在try中初始化connectedToDatabase为true。如果在尝试连接时捕获到异常,则布尔值将保持为假。

private boolean connectedToDatabase = false;

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

然后你可以创建一个if语句,如果connectedToDatabase为false,将抛出异常。只需确保该方法抛出IllegalStateException。

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

如果服务器出现故障,这将无效,因为它只会确定初始连接是否成功。

答案 1 :(得分: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;
}

在另一个类中,您应该为String分配此方法的返回值。这就是答案,现在您可以在条件语句中使用此信息,例如“if”。