MySQL数据库写入期间的空指针异常 [英] Null Pointer Exception during MySQL database write

查看:35
本文介绍了MySQL数据库写入期间的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java新手,请原谅我的无知.我正在开发一个将记录写入 MySQL 数据库的项目.我收到空指针异常错误.我无法弄清楚我做错了什么.代码如下:

I am new to java, so please excuse my ignorance. I am working on a project that will write records into a MySQL database. I am getting a null pointer exception error. I cannot figure out what I am doing wrong. Following is the code:

package studentrecord;


import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StudentRecord {

    private Scanner in = new Scanner(System.in);
    private PrintStream out = System.out;
    private Map<Integer, Student> students = new HashMap<Integer, Student>();
    private Map<String, Mentor> mentors = new HashMap<String, Mentor>();

    private static Connection connection = null;

    /**
     * @return the connection
     */
    public static Connection getConnection() {
        return connection;
    }

    static {
        // Create a connection to the registrar database
        String url = "jdbc:mysql://localhost:3306/registrar";
        String userName = "root";
        String password = "Stef1234";

        try {
            // Register the JDBC driver for MySQL.
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, userName, password);
            System.out.println("** CONNECTED TO DATABASE **");
        } catch (Exception ex) {
            Logger.getLogger(StudentRecord.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    class InvalidStudentException extends Exception {

        @Override
        public String toString() {
            return "** INVALID STUDENT **";
        }
    }

    class NoStudentsFoundException extends Exception {

        @Override
        public String toString() {
            return "** NO STUDENTS FOUND **";
        }
    }

    class InvalidMentorException extends Exception {

        @Override
        public String toString() {
            return "** INVALID MENTOR **";
        }
    }

    class NoMentorsFoundException extends Exception {

        @Override
        public String toString() {
            return "** NO MENTORS FOUND **";
        }
    }

    /**
     * Load in students from the database.
     */
    public StudentRecord() {
        try {
            Statement statement = connection.createStatement();
            ResultSet results = statement.executeQuery("SELECT * FROM student");

            // Read in each student from the results
            int numStudents = 0;
            while (results.next()) {
                int studentID = results.getInt("studentID");
                String firstName = results.getString("firstName");
                String lastName = results.getString("lastName");

                // Attempt to determine what type of student this is
                if (!results.getString("level").isEmpty()) {                 // undergraduate
                    students.put(studentID, new Undergraduate(firstName, lastName, studentID));
                } else if (!results.getString("thesisTitle").isEmpty() ||
                           !results.getString("thesisAdvisor").isEmpty()) {  // graduate
                    students.put(studentID, new Graduate(firstName, lastName, studentID));
                } else if (!results.getString("company").isEmpty()) {        // part-time
                    students.put(studentID, new PartTime(firstName, lastName, studentID));
                } else {
                    out.println("** UNKNOWN STUDENT TYPE: (" + studentID + ") "
                                + firstName + ", " + lastName + " **");
                    continue;
                }

                ++numStudents;
            }

            statement.close();

            System.out.println("** LOADED " + numStudents + " STUDENTS **");
        } catch (SQLException ex) {
            Logger.getLogger(PartTime.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        // Display menu options
        while (true) {
            System.out.print("\nStudent Record Managing System\n"
                    + "==============================\n"
                    + "1) Add Student\n"
                    + "2) Delete Student\n"
                    + "3) Query Student\n"
                    + "4) Update Student\n"
                    + "5) Add Mentor\n"
                    + "6) Query Mentor\n"
                    + "7) Exit\n\n"
                    + "Enter Option: ");

            // Do the correct action
            try {
                switch (Integer.parseInt(in.nextLine())) {
                    case 1:
                        addStudent();
                        break;
                    case 2:
                        deleteStudent();
                        break;
                    case 3:
                        queryStudent();
                        break;
                    case 4:
                        updateStudent();
                        break;
                    case 5:
                        addMentor();
                        break;
                    case 6:
                        queryMentor();
                        break;
                    case 7:
                        cleanup();
                        return;
                }
            } catch (Exception e) {
                out.println(e.toString());
            }
        }
    }

    /**
     * Adds a student.
     */
    private void addStudent() {
        out.println();

        out.print("Enter First Name: ");
        String firstName = in.nextLine();

        out.print("Enter Last Name: ");
        String lastName = in.nextLine();

        out.print("Enter ID: ");
        int ID = Integer.parseInt(in.nextLine());

        int option;
        do {
            out.print("Select Status (1 = Resident, 2 = Non-Resident): ");
            option = Integer.parseInt(in.nextLine());
        } while (!(option == 1 || option == 2));
        Student.Status status = option == 1 ? Student.Status.Resident : Student.Status.NonResident;

        int type;
        do {
            out.print("Select Type (1 = Undergraduate, 2 = Graduate, 3 = Part-Time): ");
            type = Integer.parseInt(in.nextLine());
        } while (type < 1 || type > 3);

        // Request additional attributes depending on student type
        Student student = null;
        switch (type) {
            case 1: // undergraduate
                int levelOption;
                do {
                    out.print("Select Level: (1 = Freshman, 2 = Sophomore, 3 = Junior, 4 = Senior): ");
                    levelOption = Integer.parseInt(in.nextLine());
                } while (levelOption < 1 || levelOption > 4);
                Undergraduate.Level level = levelOption == 1 ? Undergraduate.Level.Freshman
                        : levelOption == 2 ? Undergraduate.Level.Sophomore
                        : levelOption == 3 ? Undergraduate.Level.Junior
                        : Undergraduate.Level.Senior;

                student = new Undergraduate(firstName, lastName, ID, status, level);
                break;
            case 2: // graduate
                out.print("Enter Thesis Title: ");
                String thesisTitle = in.nextLine();

                out.print("Enter Thesis Advisor: ");
                String thesisAdvisor = in.nextLine();

                student = new Graduate(firstName, lastName, ID, status, thesisTitle, thesisAdvisor);
                break;
            case 3: // part-time
                in.nextLine();
                out.print("Enter Company: ");
                String company = in.nextLine();

                student = new PartTime(firstName, lastName, ID, status, company);
                break;
        }

        // Add the student to both the internal map and the database
        students.put(ID, student);
        student.add();
        out.println("** STUDENT ADDED **");
    }

    /**
     * Selects a student from the current list of students.
     * @return
     * @throws StudentRecord.NoStudentsFoundException
     * @throws StudentRecord.InvalidStudentException
     */
    private int selectStudent() throws NoStudentsFoundException, InvalidStudentException {
        // If there are no students, throw an exception
        if (students.size() == 0) {
            throw new NoStudentsFoundException();
        }

        // Display all the available students
        out.println("\nList of students\n"
                + "================");
        for (Student s : students.values()) {
            out.printf("(%d) %s %s\n", s.getStudentID(), s.getFirstName(), s.getLastName());
        }

        out.print("\nEnter ID: ");
        int ID = Integer.parseInt(in.nextLine());

        if (!students.containsKey(ID)) {
            throw new InvalidStudentException();
        }

        return ID;
    }

    /**
     * Selects a mentor from the current list of mentors.
     * @return
     * @throws StudentRecord.NoMentorsFoundException
     * @throws StudentRecord.InvalidMentorException
     */
    private String selectMentor() throws NoMentorsFoundException, InvalidMentorException {
        // If there are no mentors, throw an exception
        if (mentors.size() == 0) {
            throw new NoMentorsFoundException();
        }

        // Display all the available mentors
        out.println("\nList of mentors\n"
                + "===============");
        for (Mentor m : mentors.values()) {
            out.printf("%s %s\n", m.getFirstName(), m.getLastName());
        }

        out.print("\nEnter Full Name: ");
        String fullName = in.nextLine();

        if (!mentors.containsKey(fullName)) {
            throw new InvalidMentorException();
        }

        return fullName;
    }

    /**
     * Deletes a student.
     * @throws StudentRecord.NoStudentsFoundException
     * @throws StudentRecord.InvalidStudentException
     */
    private void deleteStudent() throws NoStudentsFoundException, InvalidStudentException {
        int index = selectStudent();
        students.get(index).delete();
        students.remove(index);
        out.println("** STUDENT DELETED **");
    }

    /**
     * Display a student's information.
     * @throws StudentRecord.NoStudentsFoundException
     * @throws StudentRecord.InvalidStudentException
     */
    private void queryStudent() throws NoStudentsFoundException, InvalidStudentException {
        students.get(selectStudent()).query();
    }

    /**
     * Updates a student's information.
     * @throws StudentRecord.NoStudentsFoundException
     * @throws StudentRecord.InvalidStudentException
     */
    private void updateStudent() throws NoStudentsFoundException, InvalidStudentException {
        Student student = students.get(selectStudent());

        // Generate base menu
        String menu = "\nUpdate\n"
                + "======\n"
                + "1) GPA\n"
                + "2) Status\n";

        // Add additional attributes to the menu depending on type of student
        if (student instanceof Undergraduate) {
            menu += "3) Level\n";
        } else if (student instanceof Graduate) {
            menu += "3) Thesis Title\n"
                    + "4) Thesis Advisor\n";
        } else if (student instanceof PartTime) {
            menu += "3) Company\n";
        }

        menu += "\nEnter Choice: ";
        out.print(menu);

        switch (Integer.parseInt(in.nextLine())) {
            case 1:
                out.print("Enter GPA: ");
                student.setGPA(Float.parseFloat(in.nextLine()));
                break;
            case 2:
                int option;
                do {
                    out.print("Select Status (1 = Resident, 2 = Non-Resident): ");
                    option = Integer.parseInt(in.nextLine());
                } while (!(option == 1 || option == 2));
                Student.Status status = option == 1 ? Student.Status.Resident : Student.Status.NonResident;
                student.setStatus(status);
                break;
            case 3:
                if (student instanceof Undergraduate) {
                    int levelOption;
                    do {
                        out.print("Select Level: (1 = Freshman, 2 = Sophomore, 3 = Junior, 4 = Senior): ");
                        levelOption = Integer.parseInt(in.nextLine());
                    } while (levelOption < 1 || levelOption > 4);
                    ((Undergraduate) student).setLevel(levelOption == 1 ? Undergraduate.Level.Freshman
                            : levelOption == 2 ? Undergraduate.Level.Sophomore
                            : levelOption == 3 ? Undergraduate.Level.Junior
                            : Undergraduate.Level.Senior);
                } else if (student instanceof Graduate) {
                    out.print("Enter Thesis Title: ");
                    ((Graduate) student).setThesisTitle(in.nextLine());
                } else if (student instanceof PartTime) {
                    out.print("Enter Company: ");
                    ((PartTime) student).setCompany(in.nextLine());
                }
                break;
            case 4:
                if (!(student instanceof Graduate)) {
                    out.println("** INVALID CHOICE **");
                }

                out.print("Enter Thesis Advisor: ");
                ((Graduate) student).setThesisAdvisor(in.nextLine());
                break;
            default:
                out.println("** INVALID CHOICE **");
                return;
        }

        student.update();
        out.println("** STUDENT UPDATED **");
    }

    /**
     * Adds a mentor.
     */
    private void addMentor() {
        out.println();

        out.print("Enter First Name: ");
        String firstName = in.nextLine();

        out.print("Enter Last Name: ");
        String lastName = in.nextLine();

        Mentor mentor = new Mentor(firstName, lastName);

        out.print("\nAdd Students\n"
                + "============\n");
        for (Student s : students.values()) {
            out.printf("(%d) %s %s\n", s.getStudentID(), s.getFirstName(), s.getLastName());
        }
        out.print("Enter a list of IDs (separated by commas): ");
        String[] ids = in.nextLine().split(",");
        for (String ID : ids) {
            try {
                mentor.addStudent(students.get(Integer.parseInt(ID)));
            } catch (Exception e) {
            }
        }


        mentors.put(firstName + ' ' + lastName, mentor);
        out.println("** MENTOR ADDED **");
    }

    /**
     * Displays the mentor's information and his list of students.
     * @throws StudentRecord.NoMentorsFoundException
     * @throws StudentRecord.InvalidMentorException
     */
    private void queryMentor() throws NoMentorsFoundException, InvalidMentorException {
        out.println("\n\nMentor Info\n"
                + "============\n"
                + mentors.get(selectMentor()).toString());
    }

    /**
     * Cleans up resources.
     */
    private void cleanup() {
        if (getConnection() != null) {
            try {
                getConnection().close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentRecord.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        StudentRecord manager = new StudentRecord();
        manager.run();
    }
}

Student.java:

Student.java:

package studentrecord;

/**
 *
 * @author Gwen
 */

import java.sql.Connection;



public abstract class Student {
    private String firstName;
    private String lastName;
    private String mentor;
    private int studentID;
    private float GPA;
    protected Connection connection = StudentRecord.getConnection();

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @return the mentor
     */
    public String getMentor() {
        return mentor;
    }

    /**
     * @param mentor the mentor to set
     */
    public void setMentor(String mentor) {
        this.mentor = mentor;
    }

    /**
     * @return the studentID
     */
    public int getStudentID() {
        return studentID;
    }

    /**
     * @param GPA the GPA to set
     */
    public void setGPA(float GPA) {
        this.GPA = GPA;
    }

    /**
     * @return the GPA
     */
    public double getGPA() {
        return GPA;
    }

    /**
     * @return the status
     */
    public Status getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(Status status) {
        this.status = status;
    }

    public enum Status { Resident, NonResident };
    private Status status;

    /**
     * Creates a student.
     * @param firstName
     * @param lastName
     * @param studentID
     * @param mentor
     * @param status
     * @param GPA
     */
    public Student(String firstName, String lastName, int studentID) {
        this(firstName, lastName, studentID, Status.NonResident);
    }

    /**
     * Creates a student.
     * @param firstName
     * @param lastName
     * @param studentID
     * @param mentor
     * @param status
     * @param GPA
     */
    public Student(String firstName, String lastName, int studentID, Status status) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.studentID = studentID;
        this.mentor = "";
        this.GPA = 4.f;
    }

    /**
     * Calculates the tuition for the student.
     * @param creditHours the number of credit hours the student has
     * @return
     */
    public abstract double calculateTuition(int creditHours);

    /**
     * Updates the database entry for the student
     */
    public abstract void update();

    /**
     * Creates the database entry for the student
     */
    public abstract void add();

    /**
     * Deletes the database entry for the student
     */
    public abstract void delete();

    /**
     * Queries the database for the student's information
     * and prints it to the screen
     */
    public abstract void query();

    @Override
    public String toString() {
        return "First Name: " + firstName + '\n' +
               "Last Name: " + lastName + '\n' +
               "Student ID: " + studentID + '\n' +
               "Status: " + status.toString() + '\n' +
               "Mentor: " + mentor + '\n' +
               "GPA: " + GPA;
    }
}

任何帮助将不胜感激!谢谢!!

Any assistance would be GREATLY appreciated!! Thanks!!

推荐答案

检查 ResultSet.getString 的文档:
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString%28int%29

Check documentation of ResultSet.getString:
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString%28int%29

String getString(int columnIndex) 抛出 SQLException

退货:列值;如果值为 SQL NULL,则返回值为空

String getString(int columnIndex) throws SQLException

Returns: the column value; if the value is SQL NULL, the value returned is null

因此,您的代码在以下位置容易受到空指针异常的影响:

According to this your code is vulnerable to null pointer exception at following places:

   if (!results.getString("level").isEmpty()) {                
    .......
   } else if (!results.getString("thesisTitle").isEmpty() ||
          !results.getString("thesisAdvisor").isEmpty()) {  
   ..........
   } else if (!results.getString("company").isEmpty()) {     
   ............

如果这些列中的任何一列包含空值,则 getString( .. ) 返回 null,因此 getString( ... ).isEmpty() 抛出空指针异常.

If any of these column contain null value, then getString( .. ) returns null, and because of this getString( ... ).isEmpty() throws null pointer exception.

这篇关于MySQL数据库写入期间的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆