PreparedStatement: SetString once and change value of variable doesn't work.
Venkat Nagam
Greenhorn
Joined: Jul 28, 2003
Posts: 10
posted
0
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.
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.
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?