Silvestrini
Silvestrini

Reputation: 445

MySQL Syntax error in Java class?

Im having trouble getting my query statement running. Says there is a syntax error at the query statement but I'm pretty sure thats how it goes but clearly Im mistaken. Here is part of the code:

private String url = "jdbc:mysql://localhost:3306/MatrixUsers";
private String dbName = "MatrixUsers";
private String driver = "com.mysql.jdbc.Driver";
private String userNameDB = "root"; 
private String passwordDB = "password1"; 

private Connection connectMe = null;
private PreparedStatement selectUsers = null;
private Statement st;
private ResultSet results;


public void validateUserFromDB() {


    try {
        Class.forName("com.mysql.jdbc.Driver");
        connectMe = DriverManager.getConnection(url, userNameDB, passwordDB);
        String newUser = "Sil";
        String query = "SELECT count(*) FROM MatrixUsers.Users WHERE userNames = ?;";

        selectUsers = connectMe.prepareStatement(query);
        selectUsers.setString(1, newUser);
        results = selectUsers.executeQuery(query);

        //System.out.println(results);
        if(results.next()) {
            String count = null;
                    count= results.getString(1);

            if(count == null)
                System.out.println("NO MATCH");
            else
                System.out.println("MATCH");

        }

        connectMe.close();


    } catch (Exception e) {
        e.printStackTrace();
    }


}

The error is this:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

Upvotes: 0

Views: 197

Answers (2)

Jens
Jens

Reputation: 69440

remove the ; after the question mark. and remove the query from results = selectUsers.executeQuery(query);

results = selectUsers.executeQuery(query); will execute the query without replacement of the placeholder. That is used for "static" queries.

results = selectUsers.executeQuery(); will execute the statement wich was prepared earlier.

Upvotes: 2

Paresh
Paresh

Reputation: 156

remove semicolon and replace line:

results = selectUsers.executeQuery(query);

by this

results = selectUsers.executeQuery();

Upvotes: 2

Related Questions