在单个JAVA类中执行两个不同的MySQL查询

时间:2013-12-15 23:06:39

标签: java mysql

当我尝试运行它时,它表示"操作无法在结果集结束时运行。"

public void multiplequeries() throws Exception{
    //try{
    //This will load the MySQL Driver, each DB has its own driver
    Class.forName("com.mysql.jdbc.Driver");
    //Setup the connection with the database
    connect = (Connection) DriverManager
            .getConnection("....these details are correct....");

    try(Statement stmt = connect.createStatement())
    {
        /*COUNT(*) should be used instead of * but it is not necessary*/

        String query = "select * from course where dept_name='Comp. Sci.'";
        ResultSet resultSet = stmt.executeQuery(query);
        int i=0;

        while (resultSet.next())
        {
            i=i+1;
        }

        System.out.println("The Total number of courses are: " + i);
    }
}

现在我有另一个需要运行的查询。它使用不同的表,结果也不同。

select ID, COUNT(DISTINCT course_id) as coursecount 
from teaches as t natural join instructor as i
where i.dept_name = 'Comp. Sci.'
group by ID

它返回教师讲授的课程数量。

架构如下:

course (**course_id**, title, dept_name, credits)
teaches (**ID**, **course_id**, **sec_id**, **semester**, **year**)
instructor (**ID**, name, dept_name, salary)

1 个答案:

答案 0 :(得分:-1)

执行下一个查询之前关闭ResultSet

public void multiplequeries() throws Exception{
//try{
//This will load the MySQL Driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
//Setup the connection with the database
connect = (Connection) DriverManager
        .getConnection("....these details are correct....");

try(Statement stmt = connect.createStatement())
{
    /*COUNT(*) should be used instead of * but it is not necessary*/

    String query = "select * from course where dept_name='Comp. Sci.'";
    ResultSet resultSet = stmt.executeQuery(query);
    int i=0;

    while (resultSet.next())
    {
        i=i+1;
    }
    resultSet.close();
    System.out.println("The Total number of courses are: " + i);
}
}