【发布时间】:2020-06-11 22:36:47
【问题描述】:
我目前在 Java 中使用 String 来运行 SQL 语句
String fruitName = "apple";
String colorOfFruit = a < b ? null : "red";
String sizeOfFruit = c > d ? null : "big";
String sql = "SELECT * FROM my_table WHERE fruit = ? " +
if (colorOfFruit != null) sql += "AND color = ? ";
if (sizeOfFruit != null) sql += "AND size = ? "
sql += "ORDER BY fruit";
int i = 1;
PreparedStatement stmt = databaseConnection.prepareStatement(sql)
stmt.setString(i++, fruitName);
if (colorOfFruit != null) stmt.setString(i++, colorOfFruit);
if (sizeOfFruit != null) stmt.setString(i++, sizeOfFruit);
ResultSet rs = stmt.executeQuery();
有什么方法可以将其转换为可以在 Java 中使用 CallableStatement 运行的 SQL 查询?我正在考虑创建一个存储过程,但我不确定如何有条件地拥有 AND 语句。
CREATE PROCEDURE MyProcedure
@fruitName NVARCHAR(50),
@colorOfFruit NVARCHAR(50),
@sizeOfFruit NVARCHAR(50)
AS
BEGIN
SELECT * FROM my_table WHERE fruit = @fruitName
-- add an and statement here if @colorOfFruit is not null
-- add another and statement here if @priceOfFruit is not null
ORDER BY fruit
END
【问题讨论】:
标签: java sql sql-server sql-server-2008 java-8