使用mysql查询在Java中连接两个数据库?

时间:2017-06-13 10:56:12

标签: java mysql

我正在尝试在java应用程序中运行SQLquery。 sqlquery连接两个数据库(不在同一服务器上)。我在这里做的是否正确:

公共职能部门:

    private DatabaseData externaldb = new DatabaseData("com.mysql.jdbc.Driver",
 "...", "...", "...");
    private DatabaseData localdb = new DatabaseData("com.mysql.jdbc.Driver",
 "...", "...", "...");
    private Connection externalconnection = null;
    private Connection localconnection = null;

    function(externalconnection, c_id, u_d);

被叫函数是:

private int function(Connection externalconnection, String c_Id, String u_Id) 
    throws SQLException{
                String query ="SELECT A.v_id, COUNT(I.v_id) AS v_count "
                        + "FROM externaldb.video_interaction I"
                        + " INNER JOIN localdb.video_additional A ON A.v_id = I.v_id"
                        + " WHERE I.c_id='" + c_id + "' AND I.user'" + u_Id +  "';";

                Statement stmt = externaldb.createStatement();
                ResultSet rs = stmt.executeQuery(query);

                int counter = 0;

                if (rs.next()){
                    counter = rs.getInt("video_count");
                }

                return counter;

            }

谢谢!

1 个答案:

答案 0 :(得分:0)

您有两个连接,您有两个数据库。本地服务器必须能够访问本地的外部和外部。然后,创建FEDERATED表,例如:

CREATE TABLE federated_table (
    id     INT(20) NOT NULL AUTO_INCREMENT,
    name   VARCHAR(32) NOT NULL DEFAULT '',
    other  INT(20) NOT NULL DEFAULT '0',
    PRIMARY KEY  (id),
    INDEX name (name),
    INDEX other_key (other)
)
ENGINE=FEDERATED
DEFAULT CHARSET=latin1
CONNECTION='mysql://fed_user@remote_host:9306/federated/test_table';

(在MySQL 5.0.13之前,使用COMMENT而不是CONNECTION。)

来自:MySQL Cross Server Select Query

更多信息:https://dev.mysql.com/doc/refman/5.7/en/federated-create-server.html