【问题标题】:SQL error or missing database (near “?”: syntax error)SQL 错误或缺少数据库(“?”附近:语法错误)
【发布时间】:2018-04-10 15:11:59
【问题描述】:
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);

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

【问题讨论】:

    标签: java jdbc sqlite prepared-statement placeholder


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      使用时否:

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

      【讨论】:

        猜你喜欢
        • 2021-04-28
        • 1970-01-01
        • 2017-02-11
        • 2021-07-31
        • 1970-01-01
        • 2017-10-18
        • 2020-12-11
        • 2018-01-19
        • 2016-08-14
        相关资源
        最近更新 更多