2

I have a SQL select query already written in java. Now i want to select few more columns. In that case i need to write column names before the index of from keyword. Like this Initial query-

StringBuffer query;
query = " Select name,age,dob from employee"

New query should be like this-

query = "select name , age , dob,city from employee"

For this i tried query= query.insert(indexof(dob),"city");

But i think this will overwrite from. My question comes down to whether insert creates enough space to insert the string or it overwrites the earlier string? Please help.

4
  • What are you trying to do here? Do you want to insert query results into stringbuffer or query strings? Are you referring to storing some prepared statements? Commented Dec 2, 2012 at 10:58
  • I am trying to build a query using string buffer. Commented Dec 2, 2012 at 11:02
  • 1
    @Abhishekkumar that is a bad idea. You should really use prepared statements and a library to build them for you. Read all about SQL injection to understand why it is hard to write good code with non-prepared, non-sanitized queries. Commented Dec 2, 2012 at 11:11
  • Also note that StringBuilder is preferred to StringBuffer (it is more efficient in the common case of not having multiple threads access it) Commented Dec 2, 2012 at 11:13

2 Answers 2

2

instead of getting index value of dob, get index value of from

query= query.insert(original.indexOf("from"),"city ");
Sign up to request clarification or add additional context in comments.

2 Comments

Wont this insert city after from?
No - indexOf returns the index of the start of the string it searches for
1

Try this:-

 StringBuffer query = new StringBuffer("Select name,age,dob from employee");
 query.insert(query.indexOf("from"), "city ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.