SQL错误或缺少数据库(接近“?”:语法错误)

时间:2017-10-29 15:03:39

标签: java jdbc sqlite prepared-statement placeholder

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");
}

显示错误:SQL错误或缺少数据库(near “?”: syntax error) 如果我只包括第一个占位符,那么它工作正常。

queryAllSongsInfo.setString(1, artist_name);

为什么我不能使用多个占位符?为什么第二个占位符不考虑用户的第二个输入?

2 个答案:

答案 0 :(得分:1)

不使用时:

queryAllSongsInfo.setString(2, "DESC");

这会将DESCASC个关键字放在两个引号之间,例如ORDER BY track 'DESC',这是不正确的。

而是直接使用查询连接,例如:

String QUERY = "SELECT * FROM "+TABLE_SONG_DETAILS +" WHERE "+TABLE_SONG_DETAILS+"."+"artist"+"=? ORDER BY track ";
if(order==ORDER_BY_DESC) {
    QUERY += "DESC";
}else {
    QUERY += "ASC";
}
PreparedStatement queryAllSongsInfo = conn.prepareStatement(QUERY);
queryAllSongsInfo.setString(1, artist_name);

答案 1 :(得分:1)

您只能将占位符用于列值。您不能将它们用于表名,列名或(在本示例中尝试过)保留字。

您可以创建两个SQL字符串,一个用于升序,另一个用于降序:

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);