Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3250686
  • 博文数量: 530
  • 博客积分: 13360
  • 博客等级: 上将
  • 技术积分: 5473
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-13 13:32
文章分类

全部博文(530)

文章存档

2017年(1)

2015年(2)

2013年(24)

2012年(20)

2011年(97)

2010年(240)

2009年(117)

2008年(12)

2007年(8)

2006年(9)

分类: Oracle

2009-11-27 21:01:15

   由于oracle没有自增长字段,有2种方法可以实现
   1.通过触发器进行触发
   2.通过事务人工实现

   oracle的触发器和存储过程是要单独布置的,而且是长驻内存,不推荐使用
   通过事务手工实现虽然麻烦,但是代价小、简单,两者性能差别几乎没有,推荐使用

人工实现方法:
   1.定义两个表
      比如Log(LogID,name,date,message)
         Log_Serial(maxLogID)
      log表用来存放正常的数据,其中LogID为varchar2或Long型,数值是惟一的
      Log_Serial用来存放当前最大的LogID号

   2.操作过程
     打开事务
     用select maxLogID from Log_Serial for update语句,即U锁,将当前表锁住,不任任何线程读写操作。
     从Log_Serial表中获取当前最大ID号,再将该ID号值+1后,存入该表中
     关闭事务

具体代码如下
public int getNextId(String tableName, String colName) throws SQLException {
        int id = 0;
        try {
            if (!isConnected())
                this.connection();
            this.transactionStart();
            String sql = "select "+colName+" from "+tableName+" for update";
            ResultSet rs = this.query(sql);
            if (rs.next()) {
                String newId = rs.getString(1) == null ? "0" : rs.getString(1);
                id = Integer.parseInt(newId);
                this.execute("update"+tableName+" set "+colName+"='" + (id+1)+"'");
            } else {
                throw new SQLException("No row of " + tableName
                        + " from table!");
            }
            this.transactionEnd();
        } catch (Exception e) {
            id = 0;
            e.printStackTrace();
            this.transactionRollback();
            throw new SQLException("error");
        }
        return id;
    }
阅读(3152) | 评论(1) | 转发(0) |
0

上一篇:配置Log4j

下一篇:java数据库操作类

给主人留下些什么吧!~~

chinaunix网友2010-01-08 09:12:04

老师啊,Oracle里面的自增是通过sequence(序列)实现的,你这样通过程序实现也可以,但是我认为通过序列会更好一点。 ——SUN