博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

从数据库中取编号一次取10个,节省数据库负担90%

Posted on 2006-05-15 10:34  wander  阅读(269)  评论(0编辑  收藏  举报

using System;
using System.Data;
using System.Data.SqlClient;

namespace GetNextID
{
 
 /// <summary>
 /// 从数据库中取编号
 /// </summary>
 public class GetNextId
 {
  private const int INCREASE_VALUE = 10;

  private  string strConn = "server=192.168.10.101;user id=sa;password=123456;data source=WANDER;database=Lx";

  private  SqlConnection DBConnection; 

  private static long m_NextID;  

  private static GetNextId m_GetNextId;

  private GetNextId()
  {
   m_NextID = GetID();
  }

  public static GetNextId GetInstance()
  {
   if ( m_GetNextId == null )
    m_GetNextId = new GetNextId();
   
   return m_GetNextId;
  }

  public long Value
  {
   get
   {
    lock( this )
    {     
     if ( m_NextID % INCREASE_VALUE == 0 )
      m_NextID = GetID();

     return ++m_NextID ;
    }
   }
  }

  private long GetID()
  {
   long lngID;

   DBConnection = new SqlConnection ( strConn );
   DBConnection.Open();

   SqlCommand comm = new SqlCommand( "GetNextID", DBConnection );
   comm.CommandType = CommandType.StoredProcedure;

   comm.Parameters.Add( "@ID", SqlDbType.BigInt, 8 );
   comm.Parameters[ "@ID" ].Direction = ParameterDirection.Output;

   comm.Parameters.Add( "@IncreaseValue", SqlDbType.Int, 4 );
   comm.Parameters["@IncreaseValue"].Value = INCREASE_VALUE;
   
   comm.ExecuteNonQuery();

   lngID = Convert.ToInt64( comm.Parameters["@ID"].Value );
   return lngID;
  }
 }//class
}//namespace


程序调用:
private GetNextId nextID1 ;
  private GetNextId nextID2 ;
  private void Form1_Load(object sender, System.EventArgs e)
  {
   nextID1 = GetNextId.GetInstance();
   nextID2 = GetNextId.GetInstance();
   
  }

  
  private void button1_Click(object sender, System.EventArgs e)
  {
   this.label1.Text = nextID1.Value.ToString()  + " " + nextID2.Value.ToString();
  }