So I have a simple function to return something from the database. I can then modify this query by adding different parameters in the WHERE clause. What would be the most elegant and efficient way to handle this?
Example:
public static getUsers(int id, string username, string email) {
Connection conn = null;
PreparedStatement stmt = null;
String sql = "";
sql = "SELECT * FROM users " .........
And that's where I'm confused about the where clause. If I do something like
"WHERE id = ? AND username = ? AND email = ?";
What happens if I call the method with only an Id, and no username or email? It'll break and I can't have that happening.
Also, it becomes hard to manage my indexes, becuase if I would do something like stmt.setInt(1, id)
, but what if I only wanted to call the method with the username, and that id would come in as null, wouldn't throw a NPE?
I'm sort of new to Java, sorry... but I'm thinking I should use overrides? should I build my where clause in a conditional statement? Any help would be appreciated.
Thanks