我想要實現搜索過濾器此表:測試對於SQL查詢裏面空
CREATE TABLE ACCOUNT(
ID INTEGER NOT NULL,
USER_NAME TEXT,
PASSWD TEXT,
FIRST_NAME TEXT,
LAST_NAME TEXT,
LAST_LOGIN DATE,
DATE_REGISTERED DATE,
ROLE INTEGER,
CAN_LOGIN INTEGER
)
;
-- ADD KEYS FOR TABLE ACCOUNT
ALTER TABLE ACCOUNT ADD CONSTRAINT KEY1 PRIMARY KEY (ID)
;
SELECT * FROM ACCOUNT
WHERE '" + searchString + "' IN (ID, USER_NAME, FIRST_NAME, LAST_NAME)
ORDER BY %S %S offset ? limit ?;
但是,當我有空搜索過濾器我得到這個錯誤:
org.postgresql.util.PSQLException: ERROR: invalid input syntax for integer: "null" Position: 30
我如何可以編輯SQL查詢的方式,如果searchString爲空,WHERE子句將被跳過?
這裏是Java方法:
public List<AccountsObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException
{
String SqlStatement = null;
if (ds == null)
{
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}
String sortDirection = sortAscending ? "ASC" : "DESC";
SqlStatement = "SELECT * FROM ACCOUNT "
+ " WHERE '" + searchString + "' IN (ID, USER_NAME, FIRST_NAME, LAST_NAME)"
+ " ORDER BY %S %S offset ? limit ? ";
String sql = String.format(SqlStatement, sortField, sortDirection);
PreparedStatement ps = null;
ResultSet resultSet = null;
List<AccountsObj> resultList = new ArrayList<>();
try
{
conn.setAutoCommit(false);
boolean committed = false;
ps = conn.prepareStatement(sql);
ps.setInt(1, firstRow);
ps.setInt(2, rowCount);
resultSet = ps.executeQuery();
resultList = ProcessorArrayList(resultSet);
conn.commit();
committed = true;
}
finally
{
ps.close();
conn.close();
}
return resultList;
}
無論你做什麼只是停下來一會兒。你的查詢看起來很奇怪。在你的應用層中,你可能有:1.串連接2.參數綁定3.串取代。如果用戶提供'searchString'會怎麼評論其餘的查詢和'DROP DATABASE'呢? – lad2025
無論如何它可能是重複的:http://stackoverflow.com/questions/36519762/search-in-postgresql-table – lad2025
這是一個類似的,但問題是不同的。 –