Search code examples
javasqldatabaseconcatenationstring-concatenation

Is there a better way than string concatenation when implementing dynamic variables into an SQL statement


I'm working in Java and I've got the following method:

    public ResultSet getRecordsWithinBoundingBox(int spillFarLeftValue, int spillFarRightValue, int spillMostDownwardValue, int spillMostUpwardValue) {
    ResultSet resultSet = null;

    try {
        Statement statement = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        String sql = "SELECT * FROM OTH WHERE (jl<=" + spillMostUpwardValue + " AND (ih>=" + spillFarLeftValue + " AND ih<="
                + spillFarRightValue+ ") OR (il<=" + spillFarRightValue + " AND il>=" + spillFarLeftValue + ")) OR (jh>="
                + spillMostDownwardValue + " AND (ih>=" + spillFarLeftValue + " AND ih<=" + spillFarRightValue + ") OR (il<="
                + spillFarRightValue + " AND il>=" + spillFarLeftValue + ")) OR (il<=" + spillFarLeftValue + " AND ih>="
                + spillFarRightValue + " AND (jl<=" + spillMostUpwardValue + " AND jl>=" + spillMostDownwardValue + ") OR (jh>="
                + spillMostDownwardValue + " AND jh>=" + spillMostUpwardValue + ")) OR (jl<=" + spillMostDownwardValue + " AND jh>="
                + spillMostUpwardValue + " AND (il>=" + spillFarLeftValue + " AND il<=" + spillFarRightValue + ") OR (ih<="
                + spillFarRightValue + " AND ih>=" + spillFarLeftValue + ")) OR (il<=" + spillFarLeftValue + " AND ih>="
                + spillFarRightValue + " AND jl<=" + spillMostDownwardValue + " AND jh>=" + spillMostUpwardValue + ")";

        resultSet = statement.executeQuery(sql);

        statement.close( );
        resultSet.close( );
    } catch (SQLException ex) {
        Logger.getLogger(DatabaseInteractor.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultSet;
}

As you can see, I am currently using the a huge string to pull data from my database and I was told that this wasn't the best solution. But sadly I wasn't also told what I should be doing instead. But I feel like it's risky to put together an SQL statement the way I am doing it now, And I'd like to know about alternative ways to get to the same result.


Solution

  • A good alternative is using prepared statements : Example

    sql= "INSERT INTO imt_database.Comment(error_id,user,content) VALUES (?,?,?);";
            try{
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(URL,"root","toor");
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, Error_id);
                ps.setString(2, User);
                ps.setString(3, Content);
                ps.executeUpdate();
            }catch(Exception e)