0

I started using Java with MySQL for the first time, so I don't know it well yet. I need help with this class. For some reason does the "if" make my programm crash. The class should scan the name and check if it's already used or not. When it's not used it should enter the name in the database.

I get the following error:

java.lang.NullPointerException at 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();
            }
        }

    }

}
Gintoki
  • 120
  • 15
  • It looks like you have extra space between: `System. in` and `in .nextLine()`. These should be `System.in` and `in.nextLine()` respectively. This might fix the problem if it's your `name` variable that refers to the `null`. – JimmyM Jan 20 '15 at 15:26
  • Looks like I did this mistake when I copy pasted. – Gintoki Jan 21 '15 at 07:47

0 Answers0