使用多个“?"的一个参数的PreparedStatement. [英] PreparedStatement,using one parameter for multiple "?"

查看:551
本文介绍了使用多个“?"的一个参数的PreparedStatement.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个插入(如果不存在)查询,如下所示.

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

我正在使用JDBC PreparedStatement如下执行上述查询

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.

如果相关,我不会使用spring或任何其他框架.

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

推荐答案

在这种情况下,您可能会使用SQL变量.这不是一个通用的解决方案. 而且,许多SQL供应商特定的变体也知道这种不存在时插入"构造,不需要这种过时的代码.

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

这篇关于使用多个“?"的一个参数的PreparedStatement.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆