有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何正确地为PreparedStatement创建sql查询(字符串),该语句的值在查询中重复出现?

我有这样的疑问

BEGIN IF NOT EXISTS (
    SELECT * FROM some_table with(nolock) 
    WHERE col_1 = ? and col_2 = ? and col_3 = ?)
    BEGIN
        INSERT INTO some_table (col_1, col_2, col_3, col_4, col_5, col_6,
            col_7, col_8, col_9, col_10, col_11, col_12, cdate) 
        VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, convert(date, GETDATE()))
    END
    ELSE
    BEGIN 
    UPDATE some_table 
        SET col_4 = col_4 + ?,
            col_5 = col_5 + ?,
            col_6 = col_6 + ?,
            col_7 = col_7 + ?,
            col_8 = col_8 + ?,
            col_9 = col_9 + ?,
            col_10 = col_10 + ?,
            col_11 = ?
        WHERE col_1 = ? and col_2 = ? and col_3 = ?
    END
END

由于一些要求,我不得不将这个{}保存在{}中,这对我来说已经非常痛苦了。但我为此创建了PreparedStatement,如下所示:

PreparedStatement preparedStatemnt = conn.prepareCall(sqlQuery)) {
preparedStatemnt.setInt(1, value1);
preparedStatemnt.setString(2, value2);
preparedStatemnt.setString(3, value3);

preparedStatemnt.setInt(4, value1);
preparedStatemnt.setString(5, value2);
preparedStatemnt.setString(6, value3);
preparedStatemnt.setInt(7, value4);
preparedStatemnt.setInt(8, value5);
preparedStatemnt.setInt(9, value6);
preparedStatemnt.setInt(10, value7);
preparedStatemnt.setInt(11, value8);
preparedStatemnt.setInt(12, value9);
preparedStatemnt.setInt(13, value10);
preparedStatemnt.setInt(14, value11);
preparedStatemnt.setString(15, value12);

preparedStatemnt.setInt(16, value4);
preparedStatemnt.setInt(17, value5);
preparedStatemnt.setInt(18, value6);
preparedStatemnt.setInt(19, value7);
preparedStatemnt.setInt(20, value8);
preparedStatemnt.setInt(21, value9);
preparedStatemnt.setInt(22, value10);
preparedStatemnt.setInt(23, valye11);
preparedStatemnt.setInt(24, value1);
preparedStatemnt.setString(25, value2);
preparedStatemnt.setString(26, value3);

就像你们在这里看到的一样,我必须输入的值可以重复,我宁愿避免,但我不知道是否有任何可能性

这是我的问题,我的意思是,有没有办法以一种String.fromat工作的方式创建这个语句

String.format("%1s, %1s, %1s, %1s", value1); // so the First(1) value is putted into all 4 places

我在考虑使用String.format来创建它们,但我几乎可以肯定这是不安全的,是吗?或者有人可以给我其他建议如何处理这样的语句,这将非常有用,因为我有很多这样的查询,我必须创建

另外,我不能使用存储过程


共 (0) 个答案