1 32 33 34 52 package stockonline.ejb.sql; 53 54 import java.sql.*; 55 import javax.sql.*; 56 import javax.naming.*; 57 58 61 62 public class SeqGenerator 63 { 64 final static boolean verbose = false; 65 final static String oralceSqlForAccountID = "SELECT SubaccountSeq.nextval FROM dual"; 66 final static String oralceSqlForTxID = "SELECT StocktransactionSeq.nextval FROM dual"; 67 68 70 public SeqGenerator () {} 71 72 76 public static int getNextAccountID(Connection con) 77 throws Exception 78 { 79 return getNext(con, oralceSqlForAccountID); 80 } 81 82 86 public static int getNextAccountID(DataSource ds) 87 throws Exception 88 { 89 Connection con = ds.getConnection(); 90 int id = getNext(con, oralceSqlForAccountID); 91 con.close(); 92 93 return id; 94 } 95 96 100 public static int getNextAccountID(String resName) 101 throws Exception 102 { 103 Connection con = getConnection(resName); 104 int id = getNext(con, oralceSqlForAccountID); 105 con.close(); 106 107 return id; 108 } 109 110 112 116 public static int getNextTxID(Connection con) 117 throws Exception 118 { 119 return getNext(con, oralceSqlForTxID); 120 } 121 122 126 public static int getNextTxID(DataSource ds) 127 throws Exception 128 { 129 Connection con = ds.getConnection(); 130 int id = getNext(con, oralceSqlForTxID); 131 con.close(); 132 133 return id; 134 } 135 136 140 public static int getNextTxID(String resName) 141 throws Exception 142 { 143 Connection con = getConnection(resName); 144 int id = getNext(con, oralceSqlForTxID); 145 con.close(); 146 147 return id; 148 } 149 150 154 private static int getNext(Connection con, String sql) 155 throws Exception 156 { 157 PreparedStatement pstmt = null; 158 ResultSet rs = null; 159 160 try 161 { 162 if(verbose) System.out.println(sql); 163 pstmt = con.prepareStatement(sql); 164 rs = pstmt.executeQuery(); 165 166 if (!rs.next()) 167 throw new SQLException("Failed to create the sequence: " + sql); 168 169 int seqVal = rs.getInt(1); 170 if(verbose) System.out.println("SeqGenerator.getNext(): " + "The generated seqVal = " + seqVal); 171 172 return seqVal; 173 } 174 catch(SQLException ex) 175 { 176 System.err.println("SeqGenerator.getNext(): " + ex.getMessage()); 177 throw new Exception (ex.toString()); 178 } 179 finally 180 { 181 if(rs!=null) rs.close(); 182 if(pstmt!=null) pstmt.close(); 183 } 184 } 185 186 private static Connection getConnection (String resName) 189 throws Exception 190 { 191 try 192 { 193 if(verbose) System.out.println("To look up datasource: " + resName); 194 DataSource ds = (DataSource)(new InitialContext()).lookup(resName); 195 196 return ds.getConnection(); 197 } 198 catch (javax.naming.NamingException e1) 199 { 200 System.err.println(e1.toString()); 201 throw new Exception (e1.toString()); 202 } 203 catch(SQLException e2) 204 { 205 System.err.println(e2.toString()); 206 throw new Exception (e2.toString()); 207 } 208 } 209 } | Popular Tags |