Is there any function or library which can be used to clean the user input. Like for example if the user input a text called baily's
then i should escape the '
before sending it to mysql query. Similarly i should be able to filter null characters and \n, \t, \r etc.. Like in PHP we have mysql_real_escape_string($input)
is there anything in Java to do this ?
replace() Method to Remove Substring in Java The first and most commonly used method to remove/replace any substring is the replace() method of Java String class. The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
Java is a programming language where we can see a huge amount of built-in functions to fulfill our purpose of string manipulations. You can do various things in Java programming like getting the length of a string, finding the character within a string, String concatenation, getting substring, string modification, etc.
In Java, you don't usually do this by hand.
Instead you'll use a PreparedStatement
and pass in any arguments to your SQL statement via explicit setString()
or setObject()
methods.
This way the JDBC driver will handle it (either by doing the necessary escaping or by sending the SQL statement separately form the arguments, depending on the DB).
For example, your code could look like that (using prepareStatement()
):
Connection c = ...; // get Connection from somehwere
PreparedStatement stmt = c.prepareStatement("SELECT * FROM BOOKS WHERE TITLE = ?");
stmt.setString(1, userInput);
ResultSet result = stmt.executeQuery();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With