⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbsequencemanager.java

📁 基于JSP的家电连锁超市管理系统 数据库也在文件内
💻 JAVA
字号:
package electric.electricUtils;
import java.sql.*;
import java.util.*;
public class DbSequenceManager
{
	//读取现在的自动递增的值是多少
	private static final String LOAD_ID="SELECT SEQUENCEID FROM SEQUENCETABLE WHERE TABLENAME=?";
	//将递增后的值存入数据库中
	private static final String UPDATE_ID=
	   "UPDATE SEQUENCETABLE SET SEQUENCEID=? WHERE TABLENAME=? AND SEQUENCEID=?";
	//	建立递增信息
	private static final String INSERT_ID="INSERT INTO SEQUENCETABLE(SEQUENCEID,TABLENAME) VALUES(?,?)";
	//自动增长的递增率
	private static final int INCREMENT=1;
	//取得将对哪些表进行操作
	private static DbSequenceManager[] managers;
	private int type;      //Table所对应的数字值
	private int currentID; //当前结果集里所指的ID
	public DbSequenceManager(int type)
	{
		this.type=type;
		currentID=0;
	}
	static 
	{
		managers=new DbSequenceManager[FinalConstants.TABLENUM];
		for(int i=0;i<managers.length;i++)
		{
			managers[i]=new DbSequenceManager(i);
		}
	}
	//读取下一个递增的值是多少
	public static int nextID(int type)
	{
		return managers[type].nextUniqueID();
	}
	//锁定将要获得下一个递增值的方法
	public synchronized int nextUniqueID()
	{
		//调用类中的方法
		getNextBlock();
		int id=currentID+INCREMENT;
		return id;
	}
	//读取已经存在的值
	private void getNextBlock()
	{
		boolean success=false;  //判断更新一条是否成功
		Connection con=null;
		PreparedStatement pstmt=null;
		try
		{
			//获得连接
			con=DbConnectionManager.getConnection();
			pstmt=con.prepareStatement(LOAD_ID);
			pstmt.setInt(1,type);
			ResultSet rs=pstmt.executeQuery();
			//判断是否有信息存在,如果没有,将创建递增值信息
			if(!rs.next())
			{
				pstmt=con.prepareStatement(INSERT_ID);
				pstmt.setInt(1,currentID);
				pstmt.setInt(2,type);
				pstmt.executeQuery();
			}
			else
			{
				currentID=rs.getInt(1);
			}
			pstmt.close();
			int newID=currentID+INCREMENT;
			pstmt=con.prepareStatement(UPDATE_ID);
			pstmt.setInt(1,newID);
			pstmt.setInt(2,type);
			pstmt.setInt(3,currentID);
			success=pstmt.executeUpdate()==1;
			if(success)
			{
				this.currentID=currentID;
			}
		}
		catch(Exception sqle)
		{
			sqle.printStackTrace();
		}
		finally  //关闭连接等信息,释放资源
		{
			try
			{
				pstmt.close();	
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			try
			{
				con.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}
		if(!success)     //如果没有更新成功,警告并继续执行一次
		{
			System.out.println("WARNING:failed to obtain next ID block due to"+
			                 "thread contention.Trying again...");
			this.getNextBlock();
		}
		
	}
	
	public static void main(String args[])
	{
		
		nextID(3);
	}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -