1 19 package org.lucane.server.database.util; 20 21 import org.lucane.server.database.DatabaseAbstractionLayer; 22 import org.lucane.server.Server; 23 24 import java.sql.SQLException ; 25 import java.sql.Connection ; 26 import java.sql.PreparedStatement ; 27 import java.sql.ResultSet ; 28 29 32 public class Sequence 33 { 34 private String table; 35 private String field; 36 private int nextId; 37 38 44 public Sequence(String table, String field) 45 { 46 this.table = table; 47 this.field = field; 48 this.nextId = -1; 49 } 50 51 56 public synchronized int getNextId() 57 throws SQLException 58 { 59 if(nextId < 0) 60 initFromDatabase(); 61 62 return nextId++; 63 } 64 65 68 private void initFromDatabase() 69 throws SQLException 70 { 71 this.nextId = 0; 72 73 DatabaseAbstractionLayer layer = Server.getInstance().getDBLayer(); 74 Connection c = layer.getConnection(); 75 PreparedStatement select = c.prepareStatement( 76 "SELECT max(" + field + ")+1 FROM " + table); 77 78 ResultSet r = select.executeQuery(); 79 if(r.next()) 80 this.nextId = r.getInt(1); 81 82 r.close(); 83 select.close(); 84 c.close(); 85 } 86 } | Popular Tags |