您的位置:首页 > 数据库 > Oracle

oracle中如何使用序列

2008-10-15 12:15 357 查看
//sequenceName为序列名,length为显示序列的长度例如显示为(0000001)

public String getCircSequence(String sequenceName, int length) throws CircException
{

Connection conn = null;
StringBuffer sb = null;

try
{
conn =JdbcConnection.getInstance().getConnection();//获取链接
int key = nextSequenceNumber(conn, sequenceName);//获取序列
if (key <= 0) return null;
sb = new StringBuffer(length);
String k = Integer.toString(key);

//想要显示的长度减掉获取序列的长度,将得到的长度用0 补位
int padSize = length - k.length();
for (int i = 0; i < padSize; i++) sb.append('0');
sb.append(key);

} catch (Throwable e)
{
e.printStackTrace();
throw new CircException(kDBReadError);

} finally
{
try
{
if (conn != null) conn.close();
} catch (Throwable e)
{
e.printStackTrace();
}
}

if (sb != null) return new String(sb);
else return null;
}

//获知取序列

public int nextSequenceNumber(Connection cc, String seqName) throws SQLException
{
if (cc == null) throw new SQLException();
int k = 0;
Statement stat = cc.createStatement();
ResultSet rs = stat.executeQuery("SELECT "+seqName+".nextval from dual");
if (rs != null && rs.next())
k = rs.getInt(1);
rs.close();
stat.close();

return k;
}

public static void main(String[] args)
{
CircSequence circSequence = new CircSequence();
try
{
String seq = circSequence.getCircSequence("CIR_SEQ_USL_V_USERID", 10);
System.out.println(seq);
} catch (Throwable e)
{
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: