1 16 package org.outerj.daisy.jdbcutil; 17 18 import org.apache.avalon.framework.logger.Logger; 19 20 import javax.sql.DataSource ; 21 import java.sql.SQLException ; 22 import java.sql.Connection ; 23 import java.sql.PreparedStatement ; 24 import java.sql.ResultSet ; 25 26 public class SqlCounter { 27 private DataSource dataSource; 28 private Logger logger; 29 private String tableName; 30 31 public SqlCounter(String tableName, DataSource dataSource, Logger logger) { 32 this.tableName = tableName; 33 this.dataSource = dataSource; 34 this.logger = logger; 35 } 36 37 private Logger getLogger() { 38 return logger; 39 } 40 41 public long getNextId() throws SQLException { 42 synchronized (this) { 43 Connection conn = null; 44 PreparedStatement stmt = null; 45 ResultSet rs = null; 46 long maxid = 0; 47 try { 48 conn = dataSource.getConnection(); 49 stmt = conn.prepareStatement("select maxid from " + tableName); 50 rs = stmt.executeQuery(); 51 if (!rs.next()) { 52 getLogger().info(tableName + " table did not contain a record, will start numbering from 1."); 53 } else { 54 maxid = rs.getLong(1); 55 } 56 57 maxid++; 58 59 stmt.close(); 60 stmt = conn.prepareStatement("update " + tableName + " set maxid = ?"); 61 stmt.setLong(1, maxid); 62 int updatedRows = stmt.executeUpdate(); 63 64 if (updatedRows == 0) { 65 stmt.close(); 66 stmt = conn.prepareStatement("insert into " + tableName + "(maxid) values(?)"); 67 stmt.setLong(1, maxid); 68 stmt.execute(); 69 } 70 } finally { 71 if (stmt != null) { 72 try { 73 stmt.close(); 74 } catch (Throwable e) { 75 getLogger().error("Error closing prepared statement.", e); 76 } 77 } 78 if (conn != null) { 79 try { 80 conn.close(); 81 } catch (Throwable e) { 82 getLogger().error("Error closing datasource connection.", e); 83 } 84 } 85 } 86 return maxid; 87 } 88 } 89 } 90 | Popular Tags |