Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement,using one parameter for multiple "?"

I have a insert if not exists query as below.

BEGIN
    IF NOT EXISTS (SELECT * FROM tbl_sampleTable WHERE name = ? or subject = ?)
    BEGIN
        INSERT INTO tbl_sampleTable VALUES (?,?)
    END
END

I am executing the above query with JDBC PreparedStatement as below

    pst.setString(1, name);
    pst.setString(2, subject);
    pst.setString(3, subject);
    pst.setString(4, name);
    pst.executeUpdate();

I am getting these name and subject as method parameters, is there anyway i can provide values for multiple "?" with same parameter as they are same, instead of mentioning them two times each.

Edit: I don't use spring or any other framework, if it is relevant.

like image 825
raviraja Avatar asked Jun 13 '26 11:06

raviraja


2 Answers

JDBC doesn't support named parameters, but Spring JDBC provides this functionality with NamedParameterJdbcTemplate

like image 125
RipperJugo Avatar answered Jun 17 '26 22:06

RipperJugo


You need to add some wrapper, without using Spring (NamedParameterJdbcTemplate) you can try other as HTTP-RPC framework

The org.httprpc.sql.Parameters class provided by the HTTP-RPC framework brings named parameter support to JDBC. The parse() method of this class is used to create a Parameters instance from a JPA-like SQL query; for example:

SELECT * FROM user WHERE first_name LIKE :pattern or last_name LIKE :pattern

It takes a string or reader containing the query text as an argument:

 Parameters parameters = Parameters.parse(sqlReader);

The getSQL() method of the Parameters class returns the processed query in standard JDBC syntax. This value can be used in a call to Connection#prepareStatement():

PreparedStatement statement = connection.prepareStatement(parameters.getSQL());

Parameter values are specified via the put() method:

parameters.put("pattern", pattern);

The values are applied to the statement via the apply() method:

parameters.apply(statement);

like image 35
user7294900 Avatar answered Jun 17 '26 21:06

user7294900



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!