Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
up vote 2 down vote accepted

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? 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.

share|improve this answer
    
Thanks @blackpanther I understand the concept of String formatting – SarabjeetSingh Mar 31 '13 at 9:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.