PreparedStatement,using one parameter for multiple “?”

妖精的绣舞 提交于 2019-12-02 09:53:43

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

Just in this case you might use SQL variables. It is not a general solution. And also many SQL vendor specific variants know such insert-when-not-exists constructs, not needing such archaic code.

BEGIN
    DECLARE @MyName varchar(100);
    DECLARE @MySubject varchar(100);
    SET @MyName = ?;
    SET @MySubject = ?;
    IF NOT EXISTS (SELECT * FROM tbl_sampleTable WHERE name = @MyName OR subject = @MySubject)
    BEGIN
        INSERT INTO tbl_sampleTable(subject, name) VALUES (@MySubject, @MyName)
    END
END

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

Usefull trick in this situation is to declare variables.

You bind the values to the variables only once and you can use them several times in your PL/SQL block.

DECLARE
  l_name tbl_sampleTable.name%TYPE := ?;
  l_subject tbl_sampleTable.subject%TYPE := ?;
BEGIN
    IF NOT EXISTS (SELECT * FROM tbl_sampleTable WHERE name = l_name  or subject = l_subject )
    BEGIN
        INSERT INTO tbl_sampleTable (name,subject)
        VALUES (l_name ,l_subject )
    END
END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!