/*
 * Created on 21.01.2004
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */

/**
 * @author gfiala
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
import java.sql.*;

public class updaters2 { 
		private static ResultSet rs;
		private static Connection conn;
		public static void main(String args[]) throws Exception { 
				Class.forName("org.postgresql.Driver"); 
				conn = DriverManager.getConnection("jdbc:postgresql://localhost:5750/jurka","jurka",""); 
				Statement stmt = conn.createStatement(); 
 				
				setupDB(conn); 
				doTest(false);
				printContents("1 times next:");
				
				setupDB(conn); 
				doTest(true);
				printContents("2 times next:");
				rs.close(); 
				stmt.close(); 
				conn.close(); 
		} 
		private static void setupDB(Connection conn) throws SQLException { 
				Statement stmt = conn.createStatement(); 
				try { 
						stmt.executeUpdate("DROP TABLE mytesttable"); 
				} catch (SQLException sqle) { 
						conn.rollback(); 
				} 
				stmt.executeUpdate("CREATE TABLE mytesttable(a int primary key, b text)"); 
				stmt.executeUpdate("INSERT INTO mytesttable VALUES (1,'hello')"); 
				stmt.executeUpdate("INSERT INTO mytesttable VALUES (2,'my')"); 
				stmt.executeUpdate("INSERT INTO mytesttable VALUES (3,'world')"); 
				rs = stmt.executeQuery("SELECT * FROM mytesttable  order by a FOR UPDATE OF mytesttable;"); 
		} 
		private static void printContents(String s) throws SQLException {
			rs.beforeFirst();
			System.out.println(s + " (using same ResultSet)");
			while(rs.next()) System.out.println("a:" + rs.getInt(1) + " b:" + rs.getString(2));
			System.out.println();
			//now show whats really in there:
			Statement stmt=conn.createStatement();
			ResultSet rs1=stmt.executeQuery("SELECT * FROM mytesttable  order by a FOR UPDATE OF mytesttable;");
			System.out.println(s + " (using other ResultSet)");
			while(rs1.next()) System.out.println("a*:" + rs1.getInt(1) + " b*:" + rs1.getString(2));
			System.out.println();
		}
		private static void doTest(boolean twoTimesNext) throws SQLException {
			rs.first(); 
			rs.next();
			rs.updateString(2,"aaa"); 
			rs.updateRow(); 
			rs.previous();//now i'am at record 1, definitely.
			rs.next();//now it's still at record 1, it seems as if this had no effect despite it's result is "true"!
			if(twoTimesNext) rs.next();//now it's at record 3 - but where is 2?
			rs.updateString(2,"zzz"); 
			rs.updateRow();			
		}
}

