得到表tablename的新的id号

来源:互联网 发布:游戏程序员要学什么 编辑:程序博客网 时间:2024/06/05 08:28

public class PublicBean {

 public synchronized static int getNextId(String tableName) { //得到表tablename的新的id号
    return getNextId(null, tableName, 1);
  }

 public synchronized static int getNextId(Connection conn, String tableName,
                                           int count) { //得到表tablename的新的id号
    int id = 0;
    Connection conntemp = conn;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String sqlstr = "";
    try {
      if (conntemp == null) {
        conntemp = PoolManage.getBusinessConnectNoPool();
      }
      stmt = conntemp.prepareStatement(
          "SELECT * FROM SYS_IDCREATOR WHERE TableName=?");
      System.out.println("getnextid " + tableName);
      stmt.setString(1, tableName);
      rs = stmt.executeQuery();

      if (rs.next()) {
        id = rs.getInt("MAXID") + 1;
        sqlstr = "UPDATE SYS_IDCREATOR SET MAXID=?" +
            " WHERE TableName=?";
      }
      else {
        id = 1;
        sqlstr = "INSERT INTO SYS_IDCREATOR (MAXID,TableName) VALUES (?,?)";
      }
      PoolManage.closeDB(null, rs, stmt);
      stmt = conntemp.prepareStatement(sqlstr);
      stmt.setInt(1, id + count - 1);
      stmt.setString(2, tableName);
      stmt.execute();
    }
    catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error: " + e);
    }
    finally {
      PoolManage.closeDB(conn == null ? conntemp : null, rs, stmt);
    }
    return id;
  }

}

原创粉丝点击