简体   繁体   中英

equivalent of String.Format() in Java

I have this peace of code :

String query = "SELECT * FROM utilisateurs WHERE pseudo = '" +  pseudo.getText()+ "' AND password = '" + new String(password.getPassword()) + "'";

My question is : isn't there any other method to concat these variables with the string ?

In C# I was using the method String.Format() method as :

String query = String.Format("SELECT * FROM utilisateurs WHERE pseudo = '{0}' AND password = '{1}'", pseudo.getText(), new String(password.getPassword()));

String.format() can be used to format Strings, Javadoc .

public static String format(String format, Object... args)

Returns a formatted string using the specified format string and arguments.

However when it comes to building SQL query strings the preferred way is to use PreparedStatement ( Javadoc ) as it:

  • protects you from SQL injection
  • allows the database to cache your query (build the query plan once)

Your code using a PreparedStatement might look like below:

final PreparedStatement pstmt = con.prepareStatement(
    "SELECT * FROM utilisateurs WHERE pseudo = ? AND password = ?");
pstmt.setString(1, pseudo.getText());
pstmt.setString(2, new String(password.getPassword()));
final ResultSet rs = pstmt.executeQuery();

As others have said, String.format is the direct equivalent, but you should use a PreparedStatement instead. From the documentation :

In the following example of setting a parameter, con represents an active connection:

 PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00) pstmt.setInt(2, 110592) 

Using a PreparedStatement instead of String.format will protect your code from SQL injection.

Java has similar method to format your strings. String.format()

However, if you choose to use PreparedStatement , you can read the documentation here

From the documentation:

PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)

To answer your question directly, as others have mentioned as well, use String.Format, here is a good resource for that: How to use java.String.format in Scala? .

However, in this particular example, the real answer is not to do string substitution, but to use arguments in the SQL statement.

Something like:

query = 
String query = "SELECT * FROM utilisateurs WHERE pseudo = ? AND password = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, pseudo.getText());
ps.setString(2, password.getPassword());
ResultSet rs = ps.executeQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM