gpt4 book ai didi

java - SQL 错误或丢失数据库( “?” : syntax error) 附近

转载 作者:行者123 更新时间:2023-11-30 02:20:29 27 4
gpt4 key购买 nike

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 错误或缺少数据库(“?”附近:语法错误)如果我只包含第一个占位符,那么它就可以正常工作。

queryAllSongsInfo.setString(1, artist_name);

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

最佳答案

您只能对列值使用占位符。您不能将它们用于表名、列名或(正如您在本示例中尝试的那样)保留字。

您可以创建两个 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);

关于java - SQL 错误或丢失数据库( “?” : syntax error) 附近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com