0

我正在制作INSERT一个 sql 数据库。并且发生了一件奇怪的事情:当我运行 downer 代码时,数据库被正确写入,但编译器给了我一个错误

java.sql.SQLException: Illegal operation on empty result set.

我还没有搜索过它,我发现它可能是由于 JDBC 驱动程序的错误(但我不这么认为)。所以我决定在这里发帖。

首先我给你数据库表:

表主题

+------------------+----------------+------------+
| subjectCode      | SubjectName    | teacherCode|
+------------------+----------------+------------+
| 1                | Maths          | 10         |
| 2                | English        | 20         |
| 3                | Greek          | 30         |
+------------------+----------------+------------+

表类

+------------------+----------------+
| ClassCode        | ClassName      |
+------------------+----------------+
| 1                | Class1         |
| 2                | Class2         |
| 3                | Class3         |
+------------------+----------------+

表课程(row 和 col 是时间表的行(小时)和列(天),它们明确地确定时间表中的课程;例如:小时 1 是一天的第一个小时)

+------------------+----------------+------------+-----------+-------+-------+
| LessonCode       | SubjectCode    | teacherCode| ClassCode |  Day  |  Hour |
+------------------+----------------+------------+-----------+-------+-------+
| 1                | James          | 10         |     1     |   1   |   1   |
| 2                | John           | 20         |     2     |   1   |   2   |
| 3                | Frank          | 30         |     3     |   1   |   3   |
+------------------+----------------+------------+-----------+-------+-------+

代码:

private void writeLesson(String subjectName, String className, int column, int row)
{
    try{
        int subjCode;
        String query="SELECT subjectCode from subject WHERE subjectName='"+subjectName+"';";
        rs = st.executeQuery(query);
        rs.next();
        subjCode  = rs.getInt("subjectCode");


        int teacherCode;
        String query1="SELECT teacherCode from subject WHERE subjectName='"+subjectName+"';";
        rs = st.executeQuery(query1);
        rs.next();
        teacherCode = rs.getInt("teacherCode");

        int classCode;
        String query2="SELECT classCode from class WHERE className='"+className+"';";
        rs = st.executeQuery(query2);
        rs.next();
        ClassCode = rs.getInt("classCode");


        String query3 ="INSERT INTO lesson (subjCode, classCode, teacherCode, day, hour) "
                + "VALUES ('" + subjCode + "',"
                + "'" + classCode + "',"
                + "'" + teacherCode + "',"
                + "'" + column + "',"
                + "'" + row + "');";
        PreparedStatement statement=con.prepareStatement(query3);
        statement.executeUpdate();
        statement.close();   
    }

    catch (Exception ex){
        System.out.println("Error db: "+ex);

重要提示:该方法writeLesson位于cycle. 我没有在一个循环中测试过这段代码,它可以工作。为什么在你看来?

解决方案:问题是在循环中,writeLesson我传递给它的方法是“空白”字符串,导致错误(这就是在 DB 上写入工作的原因,但出现错误)。

4

1 回答 1

1

您是否检查过您的 select 语句中的结果集?其中一个不是空的吗?rs.getInt() 将抛出此异常,如果 rs 为空(在这种情况下 rs.next() 返回 false)

于 2013-09-16T22:45:58.300 回答