I was just googling for "how to add records into a database with ' in them" and then stumbled upon a possible vulnerability to my program, "sql injection". I don't know much about this; I saw it first on this page. People are saying something about parametrized query.
Here is my code in java:
public int addItem(String name, String manufacturer, String desc, String id, String category, double cost) throws SQLException{
String additem = "INSERT INTO item VALUES(" + addComma(returnInQuotes(id)) + addComma(returnInQuotes(name)) + addComma(returnInQuotes(manufacturer)) +
addComma(returnInQuotes(desc)) + addComma(returnInQuotes(category)) + cost + ")";
Statement statement = con.createStatement();
return statement.executeUpdate(additem);
}
public int removeItemById(String id) throws SQLException{
String removeitembyid = "DELETE FROM item WHERE id = " + returnInQuotes(id);
Statement statement = con.createStatement();
return statement.executeUpdate(removeitembyid);
}
private String returnInQuotes(String str){
return "'" + str + "'";
}
private String addComma(String str){
return str + ",";
}
addComma
and returnInQuotes
are methods I made because I was sick of typing them in in the methods that need them.
So far I've tried my queries without the quotes, derby jdbc doesn't seem to work without them.