Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning the String in java

Tags:

java

string

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 ?

like image 869
Deepak Avatar asked Jul 11 '11 11:07

Deepak


People also ask

How do you remove contents from a string in Java?

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.

How do you edit a string in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

Can you manipulate a string in Java?

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.


1 Answers

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();
like image 74
Joachim Sauer Avatar answered Sep 23 '22 13:09

Joachim Sauer