• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PreparedStatement: SetString once and change value of variable doesn't work.

 
Venkat Nagam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gurus,
I am trying to setString once and change the value of variable in side the setString. It doesn't work and I see it's preserving first value and not taking subsequent changes in the variable.
Here is piece of code:
PreparedStatement pstmt = conn.prepareStatement("insert into testtable ( ch ) values (?)");//line1
String st = new String("123");//line2
pstmt.setString(1, st );//line3
pstmt.executeUpdate();//line4
st = new String("456");//line5
pstmt.executeUpdate();//line6
After line6, I see my testtable has two rows, but with values "123" & "123" instead "123" & "456".
If this expected behavior? Is there a way to setString once and then change variable and let this gets inserted in the database?
Thanks in advance.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34860
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, primatives and Strings are pass-by-value, not pass-by-reference.
In line 3, you are assigning the value "123" to the prepared statement. In line 5, you are having st point to a new string. The prepared statement remembers that you passed it the value "123". It doesn't know or care that you happen to be pointing to something else now.
Also, new String("456") doesn't buy you any more than "456" does.
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Venkat,
I would do it like this:

Jeanne,

In Java, primatives and Strings are pass-by-value, not pass-by-reference.

That's a great way to start a "religious war"!

Also, new String("456") doesn't buy you any more than "456" does.

Actually, it does "buy" you an extra object.
Good Luck,
Avi.
[ July 28, 2003: Message edited by: Avi Abrami ]
 
Venkat Nagam
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34860
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avi,
In Java, primatives and Strings are pass-by-value, not pass-by-reference.

What's the problem with this statement. I understand why it gets fuzzy for Objects, such as Vector. But why aren't primitives and Strings always pass-by-value?
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the story Pass-by-Value Please in the Javaranch Campfire
Dave
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic