0

I'm actually trying to execute delete from mytable where CreationDate < now() - interval '5 month'

I want to pass a parameter 5 to ?

public static final StringBuilder SQL_MY_Query= new StringBuilder(
        "delete from mytable where CreationDate < now() - interval '? month'");

ps = con.prepareStatement(SQL_MY_Query.toString());
ps.setInt(1, 5);

I'm getting an error Sql Exception org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0. How do we fix this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Your Friend
  • 1,119
  • 3
  • 12
  • 27

2 Answers2

1

The question mark must replace a token; not be in a string literal.

Try this:

public static final StringBuilder SQL_MY_Query= new StringBuilder(
        "delete from mytable where CreationDate < now() - interval ? || ' month'");

Or (based on: Using a variable period in an interval in Postgres ):

public static final StringBuilder SQL_MY_Query= new StringBuilder(
        "delete from mytable where CreationDate < now() - (? || ' month')::interval");
Community
  • 1
  • 1
cadrian
  • 7,332
  • 2
  • 33
  • 42
0

One of the below might help. Have a look.

Option 1: delete from mytable where CreationDate < now() - interval ? "

ps.setString(1, numMonth + " month");

Option 2: delete from mytable where CreationDate < now() - interval (? || ' month')"

ps.setString(1, numMonth);

Gurpreet Singh
  • 380
  • 4
  • 9