6

I am new to Java programming. I want to build a SQL query string using String.format. I already use String.format in C# and it's working fine, but not in java

String Query = String.format("insert into authentication(Id,Name,Email,Password,DOB,Gender,Phone,SQ,SA) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", signup.getId(), signup.getName(), signup.getEmail(), signup.getPassword(), signup.getDate_Of_Birth(), signup.getGender(), signup.getPhone(), signup.getSQ(), signup.getSA());

try {
    ps = con.prepareStatement(Query);
    int i = ps.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}

return i;

Here signup is bean class object. But this method is not working it only save '{0}','{1}'... in the database

Another method I use It's working fine, but more code as compared to string.format

try {
    ps = con.prepareStatement("insert into authentication Id=?,Name=?,Email=?,Password=?,DOB=?,Gender=?,Phone=?,SQ=?,SA=?,IsVerified=?,IsPay=? ");
    ps.setString(1, signup.getId());
    ps.setString(2, signup.getName());
    ps.setString(3, signup.getEmail());
    ps.setString(4, signup.getPassword());
    ps.setString(5, signup.getDate_Of_Birth());
    ps.setString(6, signup.getGender());
    ps.setString(7, signup.getPhone());
    ps.setString(8, signup.getSQ());
    ps.setString(9, signup.getSA());

    int i = ps.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}

Is it possible to build SQL query string using String.format in java?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

String formatting is used to format Java strings. They can be used when we need, for example, 2 decimal points of a floating number to be represented as a String. Please see the following article of String formatting. How to use java.String.format in Scala? However, by all means, you could use the String formatting technique. However, you will have to pay attention as to how you are using it. Instead of using numbers, you will probably have to use the C type of using a percentage sign with an s, e.g. %s for each string to be placed in the query. You will have to indicate the positioning if each of your strings to be inserted into SQL statement as shown in the link.

Using PreparedStatement is the Java convention used for executing JDBC SQL statements and therefore it should be used.

Community
  • 1
  • 1
blackpanther
  • 10,998
  • 11
  • 48
  • 78