如何将jdbc查询的结果存储为在下一个查询中使用它的关系

时间:2015-02-21 03:00:00

标签: java mysql jdbc

在JDBC中,我想执行MySQL查询并将其结果存储为关系,以便在下一个查询中使用它,因为我正在做类似这样的事情:

public static void getaData() throws Exception {

        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","xyz","abc@123");
        PreparedStatement statement1 = connection.prepareStatement("select * from table1 join table2 using(table2_id)");
        ResultSet result1 = statement1.executeQuery();

        PreparedStatement statement2 = connection.prepareStatement("select concat(first_name,' ',last_name) as full_name,  party_name, head, symbol from ("+result1+") as subTable");                       
        ResultSet result2 = statement2.executeQuery();

        System.out.printf("%-30s%-30s%-30s%-30s\n\n", "full_name", "party_name", "head", "symbol");
        while(result2.next())
            System.out.printf( "%-30s%-30s%-30s%-30s\n", result2.getString(0), result2.getString(1), result2.getString(2), result2.getString(3) );

    }

但这是抛出异常:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.jdbc.JDBC4ResultSet@60d5ad52) as subTable' at line 1

那我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

您的SQL语句错误。你不能像你一样使用FROM附近的括号。它应该是,

from "+result1+"

from ("+result+" as subtable)

以上更改将解决您的问题。

答案 1 :(得分:0)

您不需要statement1或result1。

String subTable = "select * from table1 join table2 using(table2_id)";
PreparedStatement statement2 = connection.prepareStatement("select concat(first_name,' ',last_name) as full_name,  party_name, head, symbol from ("+subTable+") as subTable");