繁体   English   中英

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

[英]How do I “simplify” my Java code for a MySQL database program?

我在下面寻求帮助。

这是我的代码:

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数据库的部分变成自己的方法(或某种类似的方法(如果您不认为这样做确实有必要,请告诉我))。 我已经在这里(和其他网站)上查看了其他人的代码,了解如何执行此操作,但是每当我尝试执行与他们所做的类似的操作时,都会收到大量的错误信息,所以这就是为什么我已经离开了。

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

提前非常感谢您。

我使用的PS软件是JetBrains IntelliJ(用于实际编码)和JetBrains DataGrip(用于制作表/数据库并检查是否发生更改)

PPS另外,一切似乎都可以正常运行,并且按预期运行。 但是,在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。 我该如何解决?

在第一步中,您可以使用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");
        }
    }

//...

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM