在没有行的结果中显示0

时间:2013-03-14 15:43:39

标签: java sql jdbc plsql

我需要编写一个与数据库连接的java程序,程序应该提示用户输入7位数ID,然后计算每个字母等级的出现次数和等级总数。

例如:学生12345 A'S:1 B'S:0 C'S:3 D'S:0 F'S:O TOTAL GRADE:4

下面我的代码工作正常,但问题是没有行的结果不会给我0 .. e.x:它只是给我A,C而且删除其他人

所以你知道如何在结果中显示0。

谢谢你

import java.sql.*; // Use classes in java.sql package
import java.util.*;

public class DDBB {

    public static void main (String args []) {
        int a;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a 7 digit Number for StudentID");
        a = in.nextInt();
        System.out.println("StudentID" +" "+ a);
        int countgrade ;
        String GRADE1;
        int totalcount;
        Connection conn =null;
        Statement st =null;
        try {
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
            // Class.forName("oracle.jdbc.driver.OracleDriver");
            String url ="jdbc:oracle:thin ....";
            conn = DriverManager.getConnection(url,"user", "password");
            // create a Statement object
            PreparedStatement st1 = conn.prepareStatement(
                "SELECT GRADE, Count(*) AS COUNT1 FROM GRADING WHERE StudentID = ? GROUP BY Grade ORDER BY GRADE");
            st1.setInt(1, a);
            ResultSet S = st1.executeQuery();
            while (S.next()) {
                countgrade = S.getInt("COUNT1");
                GRADE1 = S.getString("GRADE");
                System.out.println(GRADE1 + "'s :"+countgrade+"\n");
            }
            String Q2 ="SELECT COUNT(GRADE) AS COUNT2 FROM GRADING WHERE StudentID = ? ";
            ResultSet S1 = st1.executeQuery(Q2);
            while (S1.next()) {
                totalcount = S1.getInt("COUNT2");
                System.out.println("Total grades:"+ " " + totalcount+"\n");
            }
            S.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                // close the Statement object using the close() method
                if (st != null) {
                    st.close();
                }
                // close the Connection object using the close() method
                if (conn != null) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您好像应该使用for循环而不是while来打印成绩(或者可能只是不使用循环)。

为什么不做这样的psuedocode:

int A = B = C = D = F = 0;
/* Get results as you already are, stored in result set s */
while( s.next() )
{
    string grade = s.GetString("GRADE");
    if( grade == "A" )
        A = s.GetInt("COUNT1")
    if( grade == "B" )
        B = s.GetInt("Count1")
    /*etc*/
}

在while循环结束时,只输出“A's:”+ A +“B's:”......

当您显示最终成绩时,只需显示A + B + C + D + F.

这将其缩减为一个SQL查询,并且它将始终显示每个字母等级。