Inserting the file path into the database removes the \

I am new to java. I want to insert the file path selected from FileChooser

into the database. But when I try to do this, the path is correct before the request and after entering it into the database, it removes all backslashes present in the file path.

filepath=f.getCanonicalPath();
// some database statements....
String query="insert into table1 values('" + filepath + "')";

      

If my selected file path is:

"C: \ Users \ Documents \ hello.txt";

He inserts it like:

"C: Usersdocumentshello.txt"

+3


source to share


1 answer


Basically, you shouldn't be putting your value directly into SQL.

You have to use PreparedStatement

and set the parameter with your value. No escaping required and no risk of SQL injection.



String query = "insert into table1 values(?)";

PreparedStatement statement = connection.prepareStatement(query);
try {
   statement.setString(1, filePath);
   statement.executeUpdate();
} finally {
   statement.close();
}

      

Every time you build SQL dynamically based on user input, you should take a step back and consider parameterized SQL vigorously. (The exception is if your application is primarily a SQL development tool ...)

+9


source







All Articles