1

So I am trying to practice working with databases and I decided to make a Banking System. I am using MariaDB. I wanted to make it so the user can login and if the info doesnt match anything in the database, they have to re-enter the username and password until it matches but I cannot figure it out. This is my first time implementing sql into java so I apologize if i made any mistakes. I have researched, but the solutions I could find were using swing or javafx but i am not looking to make a gui right now. Anyway, I am not really sure what I am doing in this part.

public void loginAccount(Connection conn) throws SQLException {
        String login;
        ResultSet rs;

        do {
            System.out.print("Enter Username: ");
            Username = in.nextLine();
            System.out.print("Enter Password: ");
            Password = in.nextLine();

            login = "SELECT * FROM Person WHERE Username = ? AND AccPassword = ?";
            PreparedStatement ps = conn.prepareStatement(login);

            ps.setString(1, Username);
            ps.setString(2, Password);

            rs = ps.executeQuery(login);

        }   while (!rs.next());
    }

I keep getting java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? AND AccPassword = ?' at line 1

Also, I originally had

login = "SELECT * FROM Person WHERE Username = " +Username+ " AND AccPassword = " + Password;

But i read somewhere that it is bad practice to use +. Not sure if that is true or not.

basicange
  • 31
  • 7

2 Answers2

2

You are using the wrong method of PreparedStatement.

You should use

rs = ps.executeQuery();

so that your statement gets executed where the placeholders actually have values.

f1sh
  • 11,489
  • 3
  • 25
  • 51
2

You intended to call PreparedStatement.executeQuery()

rs = ps.executeQuery();

but instead you called a static method Statement.executeQuery(String sql)

rs = ps.executeQuery(login);
Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • thank you :) i didnt know this. The error went away, but i found that the loop keeps asking for username and password even if it matches the database. Might there be something wrong with my while(!rs.next())? – basicange Jan 12 '22 at 19:47
  • I cant see any obvious error. Try logging db statements (See https://stackoverflow.com/questions/27060563/how-to-enable-logging-for-sql-statements-when-using-jdbc). And never keep passwords in plain text! – Lesiak Jan 12 '22 at 20:06