-2

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

例如:学生 12345 A'S:1 B'S:0 C'S:3 D'S:0 F'S:O 总成绩:4

我下面的代码工作正常,但问题是 no row 的结果不会给我 0 .. ex:它只给我 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();
            }
        }
    }
}
4

1 回答 1

0

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

为什么不做这样的伪代码:

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 查询,并且始终显示每个字母的等级。

于 2013-03-14T15:59:04.043 回答