Java – SQL error or missing database (near “?” : syntax error)

SQL error or missing database (near “?” : syntax error)… here is a solution to the problem.

SQL error or missing database (near “?” : syntax error)

private static final String QUERY = "SELECT * FROM " + TABLE_SONG_DETAILS + " WHERE " + TABLE_SONG_DETAILS + "." + "artist" + "=? ORDER BY track ?";
private PreparedStatement queryAllSongsInfo = conn.prepareStatement(QUERY);

 the user inputs the artist_name and ORDER
queryAllSongsInfo.setString(1, artist_name);
if (order == ORDER_BY_DESC) {
    queryAllSongsInfo.setString(2, "DESC");
} else {
    queryAllSongsInfo.setString(2, "ASC");
}

Display error: SQL error or missing database (near "?") ": Syntax error)
If I only include the first placeholder then it works fine.

queryAllSongsInfo.setString(1, artist_name);

Why can’t I use multiple placeholders? Why doesn’t the second placeholder take into account the user’s second input?

Solution

You can only use placeholders for column values. You cannot use them for table names, column names, or (as you tried in this example) reserved words.

You can create two SQL strings, one for ascending and one for descending:

private static final String QUERY_ASC = "SELECT * FROM "+TABLE_SONG_DETAILS +" WHERE "+TABLE_SONG_DETAILS+"." +"artist"+"=? ORDER BY track ASC";
private static final String QUERY_DESC = "SELECT * FROM "+TABLE_SONG_DETAILS +" WHERE "+TABLE_SONG_DETAILS+"." +"artist"+"=? ORDER BY track DESC";

private PreparedStatement queryAllSongsInfo = conn.prepareStatement(order==ORDER_BY_DESC? QUERY_DESC:QUERY_ASC);

 the user inputs the artist_name and ORDER
queryAllSongsInfo.setString(1, artist_name);

Related Problems and Solutions