创建一个通用类来接受2个数据库连接

时间:2014-12-15 18:22:44

标签: java jdbc h2 spring-jdbc

我想创建一个类,它可以接受用户要求的2个数据库连接,主要是H2数据库和MSSQL。

有人可以提供伪代码或示例代码。怎么去呢?

我需要传递连接参数。

public class H2databaseconnection
{
private static final String DB_FILE_NAME=...

Connection properties for H2..
//Pretty simple code for h2
}

Public class connectionMSSQL{

{
Connection code for MSSQL
//Pretty simple code for MSSQL
}

我已经能够使用两个连接与数据库建立连接。

当我正在开发API时,我不明白如何使用什么参数对这些类进行特定调用,具体取决于拥有H2数据库或MSSQL数据库的人。

如果他有H2 / MSSQL,他应该通过哪些参数?

创建了一个具有main函数的类:

public connectivity {
    public static void main(String args[] _) {
        Connection con = new H2databaseconnection().getConnection();
        String query = "Select * from abc where ghj = 'a65e'";
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();
        System.out.println(colCount);

        // stmt.close();
        // con.close();

        Connection con1 = new ConnectionMSSQL().getConnection();
        String query1 = "Select * from xyz where abc = '05e'";
        Statement stmt1 = con1.createStatement();
        ResultSet rs1 = stmt1.executeQuery(query1);
        ResultSetMetaData rsmd1 = rs1.getMetaData();
        int colCount1 = rsmd1.getColumnCount();
        System.out.println(colCount1);

    }
}

我能够连接。但是如何为用户提供连接参数?

1 个答案:

答案 0 :(得分:0)

你的意思是

import java.sql.Connection;

public class PairedDatabaseConnection {

    public PairedDatabaseConnection(
        final Connection primaryConnection, final Connection secondaryConnection) {
        // validation connections are not null
        this.primaryConnection = primaryConnection;
        this.secondaryConnection = secondaryConnection;
    }

    private final Connection primaryConnection;
    private final Connection secondaryConnection;
}