0

I've tried searching for this, but then I'm not sure when how to describe it.

I have a method that formats some data from a hashmap to go into a mySQL table:

private String valuesList() {
    String valuesList = "";
    HashMap<String,String> data = getData();
    for(Map.Entry<String, String> entry : data.entrySet()) {
        String value=entry.getValue();
        valuesList+="'"+value+"',";
    }
    valuesList = valuesList.substring(0, valuesList.length() - 1);
    return valuesList;
}

Most of the time that works fine, but in some cases one of the values has an apostrophe in, which leads to an output like this:

'4577314','18-02-2017','null','4566974','null','Overseas Domestic Workers' Rights Bill','1124','null'

Note the 'Overseas Domestic Workers' Rights Bill' bit at the end. I thought that would be easy to fix by changing

valuesList+="'"+entry.getValue()+"',";

to

valuesList+="'"+entry.getValue().replace("'","")+"',";

but the method now throws a null pointer exception at that line. In fact any kind of change to that string such as .trim() does the same, throwing a null.

I'm completely stumped now

vindev
  • 2,074
  • 1
  • 11
  • 19
Dayne Dougan
  • 11
  • 1
  • 3
  • its a fault of getData() method. It returns data with null values – mlecz Mar 02 '18 at 10:27
  • You need to handle the case where `entry.getValue()` returns `null`. `"" + null` results in a string that literally contains `"null"`, but that's a special case that's handled by the language itself. – Daniel Pryden Mar 02 '18 at 10:30
  • just try this `valuesList+="'"+ (entry.getValue()==null)?"null":entry.getValue().replace("'","")+"',";` – Plirkee Mar 02 '18 at 10:33
  • 1
    I wonder if you should step back from this problem, and look at how to make an sql query. From the sounds of it, I think you're building an sql request in a string, instead of using parameterization. – matt Mar 02 '18 at 10:40
  • None of these answer my problem. getData isn't returning null, I know that this results in a string containing null but that is what I want I know I should be doing the SQL in a better way, but right now I just want this to work. Why can I not get it to remove the apostrophe or even just trim the string? – Dayne Dougan Mar 02 '18 at 11:51
  • @DayneDougan when you do "" + entry.getValue()` null will get converted to a String. When you do `"" + entry.getValue().replace("'","")` get value has returned a `null` and you are attempting to dereference that, hence the null pointer exception. – matt Mar 02 '18 at 12:20
  • 1
    Also, for the record, entry.getValue() is returning null. Dont take our word for it, your program is telling you so. If you don't believe it then make an intermediate check. `String s = entry.getValue(); if(s==null){ System.out.println("don't escape");}` – matt Mar 02 '18 at 12:27

1 Answers1

-1

You can escape quotes from value like this

value = value.replaceAll("'","''");