0

I am trying to store to my MySQL database the path of a file I uploaded to Tomcat. I have stored the path to a string named filepath, but when I execute the program, I get this error:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':\Users\Nick\Desktop\bot.png)' at line 1 " A part of the code I used:

String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();

// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
    file = new File( filePath + 
    fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
    file = new File( filePath + 
    fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}

I suppose the problem has to do with the format of the path, but I am pretty new to java, so I would really appreciate some help. Thank you in advance.

John Ruddell
  • 25,283
  • 6
  • 57
  • 86
GreatGatsby
  • 75
  • 1
  • 1
  • 11

2 Answers2

2

Either use double backslashes to escape or forward slash, or better still prepared statements.

Anthony Palmer
  • 944
  • 10
  • 15
  • 1
    Just curious... How would a prepared statement help? – PM 77-1 Sep 15 '14 at 23:19
  • Have a look at http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html – Anthony Palmer Sep 15 '14 at 23:33
  • I know what *prepared statement* is. My question was how it could help to deal with escaped characters. – PM 77-1 Sep 16 '14 at 00:35
  • Have a read of http://stackoverflow.com/questions/732561/why-is-using-a-mysql-prepared-statement-more-secure-than-using-the-common-escape – Anthony Palmer Sep 18 '14 at 17:20
  • They talk about escaping from SQL side. When assigning a text value to a Java String (to be bound to query parameter) it's still necessary to escape according to Java rules. So in this case OP has to do what you suggest in the beginning to your answer even if changing to prepared statement. – PM 77-1 Sep 18 '14 at 18:42
0
 path = path.replaceAll((char) 92 + "" + (char) 92, (char) 47 + "");
Hamidreza Sadegh
  • 2,155
  • 31
  • 33
  • You could strengthen your answer by adding an explanation, even though the code probably is quite straightforward in this case. – Magnilex Jul 02 '16 at 17:36