如何“简化”MySQL数据库程序的Java代码?

时间:2016-09-25 23:40:09

标签: java mysql database

我正在寻求以下方面的帮助。

这是我的代码:

package com.company;

import com.mysql.jdbc.exceptions.MySQLDataException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Connection mysql = null;
    PreparedStatement pst = null;
    ResultSet data = null;

    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        String connectionStringURL = "jdbc:mysql://us-cdbr-azure-west-b.cleardb.com:3306/database";
        mysql = DriverManager.getConnection(connectionStringURL, "username", "password");

        if(mysql == null)
            System.out.println("Connection Failed");
        else
            System.out.println("Success");

        System.out.println("What would you like to do?");
        System.out.println("Type 1 to display all students.");
        System.out.println("Type 2 to Add/Update students.");
        System.out.println("Type 3 to Delete students.");
        System.out.println("Type 4 to Search for a student.");

        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();

        if(input == 1)
        {
            pst = mysql.prepareStatement("SELECT * FROM Student;");
            data = pst.executeQuery();
            while (data.next()) {
                System.out.println(data.getString("studentId"));
                System.out.println(data.getString("firstname"));
                System.out.println(data.getString("lastname"));
                System.out.println(data.getInt("gpa"));
                System.out.println(data.getString("major"));
                System.out.println(data.getString("facultyAdvisor"));
                System.out.println();
            }
            data.close();
        }

        if(input == 2)
        {
            System.out.println("What would you like to do?");
            System.out.println("Type Add to add a student.");
            System.out.println("Type Update to update a student's information.");
            String answer = scan.next();

            if(answer.equals("Add"))
            {
                System.out.println("Enter the student First Name");
                String firstname = scan.next();
                System.out.println("Enter the student's Last Name");
                String lastname = scan.next();
                System.out.println("Enter the student's GPA");
                int GPA = scan.nextInt();
                System.out.println("Enter the student's Major");
                String Major = scan.next();
                System.out.println("Enter the student's Faculty Advisor");
                String FacultyAdvisor = scan.next();

                pst = mysql.prepareStatement("INSERT INTO Student (FirstName, LastName, GPA, Major, FacultyAdvisor) VALUES (?, ?, ?, ?, ?)");
                pst.setString(1, firstname);
                pst.setString(2, lastname);
                pst.setInt(3, GPA);
                pst.setString(4, Major);
                pst.setString(5, FacultyAdvisor);
                pst.executeUpdate();
            }

            if(answer.equals("Update"))
            {
                System.out.println("Please enter the student's Id");
                int id = scan.nextInt();
                System.out.println("You may only update the Major or the Advisor.  Which would you like to update?");
                System.out.println("Enter Major to update the major.");
                System.out.println("Enter Advisor to update the advisor.");
                String result = scan.next();

                if(result.equals("Major"))
                {
                    System.out.println("Please enter the new Major");
                    String Major = scan.next();
                    pst = mysql.prepareStatement("UPDATE Student SET Major = ? WHERE StudentId = ?");
                    pst.setString(1, Major);
                    pst.setInt(2, id);
                    pst.executeUpdate();
                }

                if(result.equals("Advisor"))
                {
                    System.out.println("Please enter the new Advisor");
                    String Advisor = scan.next();
                    pst = mysql.prepareStatement("UPDATE Student SEt FacultyAdvisor = ? WHERE StudentId = ?");
                    pst.setString(1, Advisor);
                    pst.setInt(2, id);
                    pst.executeUpdate();
                }
            }
        }

        if(input == 3)
        {
            System.out.println("Enter the student's ID");
            int Studentid = scan.nextInt();
            pst = mysql.prepareStatement("DELETE FROM Student WHERE StudentId = ?");
            pst.setInt(1, Studentid);
            pst.executeUpdate();
        }

        if(input == 4) {
            System.out.println("How would you like to search for students?");
            System.out.println("Type Major to search by the student's Major.");
            System.out.println("Type GPA to search by the student's GPA.");
            System.out.println("Type Advisor to search by the student's Faculty Advisor.");
            String search = scan.next();

            if (search.equals("Major")) {
                System.out.println("Enter the Student's Major");
                String major = scan.next();
                pst = mysql.prepareStatement("SELECT * FROM Student WHERE Major = ?");
                pst.setString(1, major);
                data = pst.executeQuery();
                while (data.next())
                {
                    System.out.println(data.getString("studentId"));
                    System.out.println(data.getString("firstname"));
                    System.out.println(data.getString("lastname"));
                    System.out.println(data.getInt("gpa"));
                    System.out.println(data.getString("major"));
                    System.out.println(data.getString("facultyAdvisor"));
                    System.out.println();
                }
                data.close();
            }

            if (search.equals("GPA")) {
                System.out.println("Enter the Student's GPA");
                int GPA = scan.nextInt();
                pst = mysql.prepareStatement("SELECT * FROM Student WHERE GPA = ?");
                pst.setInt(1, GPA);
                data = pst.executeQuery();
                while (data.next())
                {
                    System.out.println(data.getString("studentId"));
                    System.out.println(data.getString("firstname"));
                    System.out.println(data.getString("lastname"));
                    System.out.println(data.getInt("gpa"));
                    System.out.println(data.getString("major"));
                    System.out.println(data.getString("facultyAdvisor"));
                    System.out.println();
                }
                data.close();
            }

            if (search.equals("Advisor")) {
                System.out.println("Enter the Student's Advisor");
                String advisor = scan.next();
                pst = mysql.prepareStatement("SELECT * FROM Student WHERE FacultyAdvisor = ?");
                pst.setString(1, advisor);
                data = pst.executeQuery();
                while (data.next())
                {
                    System.out.println(data.getString("studentId"));
                    System.out.println(data.getString("firstname"));
                    System.out.println(data.getString("lastname"));
                    System.out.println(data.getInt("gpa"));
                    System.out.println(data.getString("major"));
                    System.out.println(data.getString("facultyAdvisor"));
                    System.out.println();
                }
                data.close();
            }
        }
        mysql.close();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}
}

我需要帮助的是将连接到我的MySQL数据库的顶部部分变成它自己的方法(或者某种类型的东西(如果你不相信它真的有必要这样做请告诉我) )。我已经在这里(以及其他网站)查看了其他人的代码,了解如何做到这一点,但每当我尝试做类似于他们所做的事情时,我会得到一些疯狂的错误,所以这就是为什么我'我就这样离开了。

此外,我想将每个部分(if(input == 1)等...)放入自己的方法中,以便我可以从main方法中调用它们。我多年前学过Java,到目前为止我所做的研究并没有真正帮助我。最后一件事,如果有人有任何关于如何使这更“用户友好”(< - 我能想到的事情)的提示,请告诉我。

提前非常感谢你。

P.S。我正在使用的软件是JetBrains IntelliJ(用于实际编码)和JetBrains DataGrip(用于制作表/数据库并检查是否发生了变化)

P.P.S。一切似乎都正常工作,并按照预期进行。但是在IntelliJ中,只要整个代码中存在“.prepareStatement(”某些SQL代码“)”,它就会突出显示它并告诉我“这个方法可能会调用java.lang.NullPointerException”这是我应该担心的事情?

编辑:

所以这就是我现在所拥有的:

public class Main {

private static Connection mysql;
private static PreparedStatement pst;
private static ResultSet data;

private static void method1()
{
    PreparedStatement pst = null;
    pst = mysql.prepareStatement("SELECT * FROM Student;");
    data = pst.executeQuery();
    while (data.next()) {
        System.out.println(data.getString("studentId"));
        System.out.println(data.getString("firstname"));
        System.out.println(data.getString("lastname"));
        System.out.println(data.getInt("gpa"));
        System.out.println(data.getString("major"));
        System.out.println(data.getString("facultyAdvisor"));
        System.out.println();
    }
}

private static void method2()
{
    System.out.println("What would you like to do?");
    System.out.println("Type Add to add a student.");
    System.out.println("Type Update to update a student's information.");
    String answer = scan.next();

    if(answer.equals("Add"))
    {
        System.out.println("Enter the student First Name");
        String firstname = scan.next();
        System.out.println("Enter the student's Last Name");
        String lastname = scan.next();
        System.out.println("Enter the student's GPA");
        int GPA = scan.nextInt();
        System.out.println("Enter the student's Major");
        String Major = scan.next();
        System.out.println("Enter the student's Faculty Advisor");
        String FacultyAdvisor = scan.next();

        pst = mysql.prepareStatement("INSERT INTO Student (FirstName, LastName, GPA, Major, FacultyAdvisor) VALUES (?, ?, ?, ?, ?)");
        pst.setString(1, firstname);
        pst.setString(2, lastname);
        pst.setInt(3, GPA);
        pst.setString(4, Major);
        pst.setString(5, FacultyAdvisor);
        pst.executeUpdate();
    }

    if(answer.equals("Update"))
    {
        System.out.println("Please enter the student's Id");
        int id = scan.nextInt();
        System.out.println("You may only update the Major or the Advisor.  Which would you like to update?");
        System.out.println("Enter Major to update the major.");
        System.out.println("Enter Advisor to update the advisor.");
        Scanner scanner= new Scanner(System.in);
        String result = scanner.next();

        if(result.equals("Major"))
        {
            System.out.println("Please enter the new Major");
            String Major = scanner.next();
            pst = mysql.prepareStatement("UPDATE Student SET Major = ? WHERE StudentId = ?");
            pst.setString(1, Major);
            pst.setInt(2, id);
            pst.executeUpdate();
        }

        if(result.equals("Advisor"))
        {
            System.out.println("Please enter the new Advisor");
            String Advisor = scanner.next();
            pst = mysql.prepareStatement("UPDATE Student SEt FacultyAdvisor = ? WHERE StudentId = ?");
            pst.setString(1, Advisor);
            pst.setInt(2, id);
            pst.executeUpdate();
        }
    }
}

private static void method3()
{
    System.out.println("Enter the student's ID");
    int Studentid = scan.nextInt();
    pst = mysql.prepareStatement("DELETE FROM Student WHERE StudentId = ?");
    pst.setInt(1, Studentid);
    pst.executeUpdate();
}


private static void method4()
{
    System.out.println("How would you like to search for students?");
    System.out.println("Type Major to search by the student's Major.");
    System.out.println("Type GPA to search by the student's GPA.");
    System.out.println("Type Advisor to search by the student's Faculty Advisor.");
    Scanner find = new Scanner(System.in);
    String search = find.next();

    if (search.equals("Major")) {
        System.out.println("Enter the Student's Major");
        String major = find.next();
        pst = mysql.prepareStatement("SELECT * FROM Student WHERE Major = ?");
        pst.setString(1, major);
        data = pst.executeQuery();
        while (data.next())
        {
            System.out.println(data.getString("studentId"));
            System.out.println(data.getString("firstname"));
            System.out.println(data.getString("lastname"));
            System.out.println(data.getInt("gpa"));
            System.out.println(data.getString("major"));
            System.out.println(data.getString("facultyAdvisor"));
            System.out.println();
        }
        data.close();
    }

    if (search.equals("GPA")) {
        System.out.println("Enter the Student's GPA");
        int GPA = find.nextInt();
        pst = mysql.prepareStatement("SELECT * FROM Student WHERE GPA = ?");
        pst.setInt(1, GPA);
        data = pst.executeQuery();
        while (data.next())
        {
            System.out.println(data.getString("studentId"));
            System.out.println(data.getString("firstname"));
            System.out.println(data.getString("lastname"));
            System.out.println(data.getInt("gpa"));
            System.out.println(data.getString("major"));
            System.out.println(data.getString("facultyAdvisor"));
            System.out.println();
        }
        data.close();
    }

    if (search.equals("Advisor")) {
        System.out.println("Enter the Student's Advisor");
        String advisor = find.next();
        pst = mysql.prepareStatement("SELECT * FROM Student WHERE FacultyAdvisor = ?");
        pst.setString(1, advisor);
        data = pst.executeQuery();
        while (data.next())
        {
            System.out.println(data.getString("studentId"));
            System.out.println(data.getString("firstname"));
            System.out.println(data.getString("lastname"));
            System.out.println(data.getInt("gpa"));
            System.out.println(data.getString("major"));
            System.out.println(data.getString("facultyAdvisor"));
            System.out.println();
        }
        data.close();
    }
}

public static void main(String[] args) {
    connect();

    try
    {
        System.out.println("What would you like to do?");
        System.out.println("Type 1 to Display all students.");
        System.out.println("Type 2 to Add/Update students.");
        System.out.println("Type 3 to Delete students.");
        System.out.println("Type 4 to Search for a student.");

        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();

        switch (input)
        {
            case 1:
                method1();
                break;
            case 2:
                method2();
                break;
            case 3:
                method3();
                break;
            case 4:
                method4();
                break;
            default:
                System.out.println("You chose incorrectly and this program will now terminate.");
        }
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

private static void connect()
{
    Class.forName("com.mysql.jdbc.Driver");
    String connectionStringURL = "jdbc:mysql://us-cdbr-azure-west-b.cleardb.com:3306/acsm_0a00c1270f36f77";
    mysql = DriverManager.getConnection(connectionStringURL, "b448ce74b4a1f1", "595da2aa");

    if(mysql == null)
        System.out.println("Connection Failed");
    else
        System.out.println("Success");
}

}

它到处说“mysql.preparestatement(”// ...“)”或“data。// ...”或“DriverManager.getConnection(// ...)”它们都给我同样的错误:未处理的异常:java.sql.SQLException。

如果它说“Class.forname(// ...)”,它说:未处理的异常:java.lang.ClassNotFoundException。我该如何解决这些问题?

1 个答案:

答案 0 :(得分:1)

在第一步中,您可以使用switch语句来处理菜单输入。为连接和每个输入案例创建方法。添加字段以保存mysql连接...

switch(input){
    case 1:
        method1();
        break;
}

方法

private static void method1(){
    //move code from input 1 here
}

然后你需要一个字段来保存连接

 private static Connection mysql;

编辑:

public class Main {

    private static Connection mysql;

    public static void main(String[] args) {
        connect();
        //...
    }

    private static void connect(){
            Class.forName("com.mysql.jdbc.Driver");
            String connectionStringURL = "jdbc:mysql://us-cdbr-azure-west-b.cleardb.com:3306/database";
            mysql = DriverManager.getConnection(connectionStringURL, "username", "password");
        if(mysql == null){
            System.out.println("Connection Failed");
        }else{
            System.out.println("Success");
        }
    }

//...

}