zoukankan      html  css  js  c++  java
  • Id生成器--【DRP】

    自增的id

    思路:从数据库查出当前的id,然后+1

    /**
     * 
     */
    package com.bjpowernode.drp.util;
    
    import java.awt.image.ConvolveOp;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    /**
     * @ClassName:IdGenerator
     * @Description:ID生成器
     * @author wm
     * @date 2016年1月15日下午6:41:06
     */
    public class IdGenerator {
        /**
         * 根据表名生成该表的序列
         * @param tableName
         * @return 返回生成的序列
         */
        public static int generate(String tableName){
            //TODO:id 生成器
            String sql="select value from t_table_id where table_name=?";
            Connection conn =null;
            PreparedStatement pstmt=null;
            ResultSet rs=null;
            int value=0;
            try {
                conn=DbUtil.getConnection();
                pstmt=conn.prepareStatement(sql);
                pstmt.setString(1, tableName);
                rs=pstmt.executeQuery();
                if(!rs.next()){
                    throw new RuntimeException();
                }
                value =rs.getInt("value");
                value++;
                modifyValueField(conn,tableName,value);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }finally{
                DbUtil.close(rs);
                DbUtil.close(pstmt);
                DbUtil.close(conn);
            }
            
            return value;
        }
        
        /**
         * 根据表名更新序列字段的值
         * @param conn
         * @param tableName
         * @param value
         * @throws SQLException 
         */
        private static  void modifyValueField(Connection conn,String tableName,int value) throws SQLException{
            String sql="update t_table_id set value=? where table_name=?";
            PreparedStatement pstmt=null;
            try {
                pstmt=conn.prepareStatement(sql);
                pstmt.setInt(1, value);
                pstmt.setString(2, tableName);
                pstmt.executeUpdate();
            } finally{
                DbUtil.close(pstmt);
            }
        }
        
        
        public static void main(String[] args){
            //完成测试
            int retValue=IdGenerator.generate("t_client");
            System.out.println(retValue);
        }
    }
  • 相关阅读:
    超有爱的并查集
    写给想当程序员的朋友
    POJ 1961 字符串 KMP (i-next[i])
    POJ 2406 KMP算法next数组理解
    POJ 2387 Bellman双重边
    POJ 1917 字符串替换
    POJ 1062 坑爹的聘礼(枚举等级差选择性找边)
    Linux下libxml2的使用
    浙大pat 1003
    判定一棵二叉树是否是二叉搜索树
  • 原文地址:https://www.cnblogs.com/wangmei/p/5135755.html
Copyright © 2011-2022 走看看