2013-01-10 80 views
0

我已經在按鈕單擊事件上調用了nextId的返回值,但是每當我嘗試執行按鈕單擊事件時,它都會初始化它,然後它會生成下一個請問您能否幫助我?爲一行生成ID

package util; 

import java.sql.Connection; 
import java.sql.ResultSet; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class CalendarUtil { 

    private static String buffer = ""; 
    private static int counter = 1; 

    public String nextID() { 
     final String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date()); 

     if (Long.parseLong(returnMaxId()) > 0) { 
      CalendarUtil.counter = Integer.parseInt(returnMaxId().substring(8, returnMaxId().length())); 
     } 

     if (buffer.equals(datePrefix)) { 
      CalendarUtil.counter++; 
     } else { 
      CalendarUtil.buffer = datePrefix; 
      CalendarUtil.counter = 1; 
     } 

     String suffix = ""; 

     if (CalendarUtil.counter <= 1000) { 

      if (validateRange(0, 9, CalendarUtil.counter)) { 
       suffix += "00" + counter; 
      } else if (validateRange(10, 99, CalendarUtil.counter)) { 
       suffix += "0" + counter; 
      } else if (validateRange(99, 999, CalendarUtil.counter)) { 
       suffix += counter; 
      } 
     } 

     return (datePrefix + suffix); 
    } 

    public boolean validateRange(int min, int max, int field) { 
     return field >= min && field <= max; 
    } 

    public String returnMaxId() { 
     String result = ""; 
     try { 
      DBUtil util = new DBUtil(); 
      Connection connection = util.getConnection(); 
      ResultSet rs = connection.createStatement().executeQuery("SELECT MAX(id) AS 'lastId' FROM crap "); 
      if (rs.next()) { 
       result = (rs.getString(1) != null) ? rs.getString(1) : "0"; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.out.println("Error : " + e.getMessage()); 
     } 
     return result; 
    } 
    public static void main(String[] args) { 

    } 
} 

回答

0
  result = (rs.getString(1) != null) ? rs.getString(1) : "0"; 

應該

  result = (rs.getInt(1) != null) ? rs.getInt(1) : "0"; 

但是你應該使用JDBC API的方法來獲得最後插入的id,簽出下面的代碼。

pstmt = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS); 
pstmt.executeUpdate(); 
ResultSet keys = pstmt.getGeneratedKeys(); 
keys.next(); 
key = keys.getInt(1); // gets the last inserted id 
keys.close(); 
pstmt.close(); 
conn.close(); 
} catch (Exception e) { e.printStackTrace(); } 
return key; 
}