aspose file tools
The moose likes JDBC and Relational Databases and the fly likes PreparedStatement.clearParameters(); Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "PreparedStatement.clearParameters();" Watch "PreparedStatement.clearParameters();" New topic


Paul Doherty

Joined: Jan 11, 2001
Posts: 11
Hi All,
I was wondering what the significance of using the clearParameters method of the PreparedStatement class. What exactly does it do. I have now included it in my code but prior to doing so I had no problems with not using it. Are there any cases when it is absolutely necessary?
Jim Baiter
Ranch Hand

Joined: Jan 05, 2001
Posts: 532
I think the main use of it is when you're reusing the
PreparedStatement. You can clear the parameters, then set
new ones and execute again without creating a new
Kevin Mukhar
Ranch Hand

Joined: Nov 28, 2000
Posts: 83
When using a PreparedStatement object, the parameters you set become part of the state of the object. That is, the parameters persist between uses of a PreparedStatement instance.
For example:
    String ssql = "select name, empno from emp where " +
        "name = ? and deptno = ?"
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, "JONES");
    ps.setInt(2, 3400);
    //select .... where name='JONES' and deptno=3400
    rset = ps.executeQuery();
If the code then changes the first parameter and executes another query, the PreparedStatement "remembers" that the second parameter is set to 3400:
    ps.setString(1, "SMITH");
    //select .... where name='SMITH' and deptno=3400
    rset = ps.executeQuery();
Here is what the Javadoc says about clearParameters():
"In general, parameter values remain in force for repeated use of a Statement. Setting a parameter value automatically clears its previous value. However, in some cases it is useful to immediately release the resources used by the current parameter values; this can be done by calling clearParameters."
So, as you stated, your code can work just fine without calling clearParameters(). I have no idea what those "some cases" are, and I've never needed to use clearParameters().
[This message has been edited by Kevin Mukhar (edited January 23, 2001).]
Peter Tran

Joined: Jan 02, 2001
Posts: 783
You should use a clearParameters() to be on the safe side. Especially, if you use setObject() method then the JDBC driver might keep some reference of your object around forever and not allow the GC to reclaim this object. Memory leak!
If you're only setting primitive values, then you don't need to execute this method.
I agree. Here's the link:
subject: PreparedStatement.clearParameters();