如何修复java.lang.NullPointerException错误

时间:2015-01-20 15:14:47

标签: java mysql runtime-error

我第一次开始使用Java和MySQL,所以我还不太了解它。我需要这堂课的帮助。由于某种原因,“if”使我的程序崩溃。该类应扫描名称并检查它是否已被使用。如果没有使用它,它应该在数据库中输入名称。

我收到以下错误:

显示java.lang.NullPointerException     在Registration.register(Registration.java:38)

import java.sql.*;
import java.util.Scanner;

public class Registration {
    public static String name = null;
    public static String name_db = null;
    public static Connection connection = null;
    public static Statement selectStmt = null;
    public static Statement selectStmt2 = null;
    private static Scanner in ;

    public static void register() {

        in = new Scanner(System. in );

        System.out.println("Name:");
        name = in .nextLine();

        Connection connection = null;
        Statement selectStmt = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/java", "root", "");

            selectStmt = connection.createStatement();

            ResultSet rs = selectStmt.executeQuery("SELECT name FROM staffs where name = '" + name + "';");
            if (rs.next()) {

                name_db = rs.getString("name");

            }

            if (name_db.equals(name)) {
                System.out.println("Name already exists.");
            } else {
                System.out.println("Name is available.");
                selectStmt2 = connection.createStatement();
                selectStmt2.execute("INSERT INTO `java`.`staffs` (`id`, `name`) VALUES (NULL, '" + name + "');");
            }



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                selectStmt.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

0 个答案:

没有答案