生成GUID唯一值的方法汇总(dotnet/javascript/sqlserver)

一、在 .NET 中生成
1、直接用.NET Framework 提供的 Guid() 函数,此种方法使用非常广泛。GUID(全局统一标识符)是指在一台机器上生成的数字,它保证对在同一时空中的任何两台计算机都不会生成重复的 GUID 值(即保证所有机器都是唯一的)。关于GUID的介绍在此不作具体熬述,想深入了解可以自行查阅MSDN。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string _guid = GetGuid();
Console.WriteLine("唯一码:{0}\t长度为:{1}\n去掉连接符:{2}", _guid, _guid.Length, _guid.Replace("-", ""));
string uniqueIdString = GuidTo16String();
Console.WriteLine("唯一码:{0}\t长度为:{1}", uniqueIdString, uniqueIdString.Length);
long uniqueIdLong = GuidToLongID();
Console.WriteLine("唯一码:{0}\t长度为:{1}", uniqueIdLong, uniqueIdLong.ToString().Length);
}
/// <summary>
/// 由连字符分隔的32位数字
/// </summary>
/// <returns></returns>
private static string GetGuid()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
return guid.ToString();
}
/// <summary>
/// 根据GUID获取16位的唯一字符串
/// </summary>
/// <param name=\"guid\"></param>
/// <returns></returns>
public static string GuidTo16String()
{
long i = ;
foreach (byte b in Guid.NewGuid().ToByteArray())
i *= ((int)b + );
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
/// <summary>
/// 根据GUID获取19位的唯一数字序列
/// </summary>
/// <returns></returns>
public static long GuidToLongID()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, );
}
}
}

2、用 DateTime.Now.ToString("yyyyMMddHHmmssms") 和 .NET Framework 提供的 RNGCryptoServiceProvider() 结合生成,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string uniqueNum = GenerateOrderNumber();
Console.WriteLine("唯一码:{0}\t 长度为:{1}", uniqueNum, uniqueNum.Length);
//测试是否会生成重复
Console.WriteLine("时间+RNGCryptoServiceProvider()结合生成的唯一值,如下:");
string _tempNum = string.Empty;
for (int i = ; i < ; i++)
{
string uNum = GenerateOrderNumber();
Console.WriteLine(uNum);
if (string.Equals(uNum, _tempNum))
{
Console.WriteLine("上值存在重复,按Enter键继续");
Console.ReadKey();
}
//Sleep当前线程,是为了延时,从而不产生重复值。可以把它注释掉测试看
Thread.Sleep();
_tempNum = uNum;
}
}
/// <summary>
/// 唯一订单号生成
/// </summary>
/// <returns></returns>
public static string GenerateOrderNumber()
{
string strDateTimeNumber = DateTime.Now.ToString("yyyyMMddHHmmssms");
string strRandomResult = NextRandom(, ).ToString();
return strDateTimeNumber + strRandomResult;
}
/// <summary>
/// 参考:msdn上的RNGCryptoServiceProvider例子
/// </summary>
/// <param name="numSeeds"></param>
/// <param name="length"></param>
/// <returns></returns>
private static int NextRandom(int numSeeds, int length)
{
// Create a byte array to hold the random value.
byte[] randomNumber = new byte[length];
// Create a new instance of the RNGCryptoServiceProvider.
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
// Fill the array with a random value.
rng.GetBytes(randomNumber);
// Convert the byte to an uint value to make the modulus operation easier.
uint randomResult = 0x0;
for (int i = ; i < length; i++)
{
randomResult |= ((uint)randomNumber[i] << ((length - - i) * ));
}
return (int)(randomResult % numSeeds) + ;
}
}
}

3、用 [0-9A-Z] + Guid.NewGuid() 结合生成特定位数的唯一字符串,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string uniqueText = GenerateUniqueText();
Console.WriteLine("唯一码:{0}\t 长度为:{1}", uniqueText, uniqueText.Length);
//测试是否会生成重复
Console.WriteLine("由[0-9A-Z] + NewGuid() 结合生成的唯一值,如下:");
IList<string> list = new List<string>();
for (int i = ; i <= ; i++)
{
string _uT = GenerateUniqueText();
Console.WriteLine("{0}\t{1}", list.Count, _uT);
if (list.Contains(_uT))
{
Console.WriteLine("{0}值存在重复", _uT);
Console.ReadKey();
}
list.Add(_uT);
//if (i % 200 == 0)
//{
//Console.WriteLine("没有重复,按Enter键往下看");
//Console.ReadKey();
//}
}
list.Clear();
} /// <summary>
/// 生成特定位数的唯一字符串
/// </summary>
/// <param name="num">特定位数</param>
/// <returns></returns>
public static string GenerateUniqueText(int num)
{
string randomResult = string.Empty;
string readyStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rtn = new char[num];
Guid gid = Guid.NewGuid();
var ba = gid.ToByteArray();
for (var i = ; i < num; i++)
{
rtn[i] = readyStr[((ba[i] + ba[num + i]) % )];
}
foreach (char r in rtn)
{
randomResult += r;
}
return randomResult;
}
}
}

4、用单例模式实现,由[0-9a-z]组合生成的唯一值,此文不讨论单例模式的多种实现方式与性能问题,随便弄一种方式实现,代码如下:
Program.cs 程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
CreateID createID = CreateID.GetInstance();
//测试是否会生成重复
Console.WriteLine("单例模式实现,由[0-9a-z]组合生成的唯一值,如下:");
IList<string> list = new List<string>();
for (int i = ; i <= ; i++)
{
string strUniqueNum = createID.CreateUniqueID();
Console.WriteLine("{0}\t{1}", list.Count, strUniqueNum);
if (list.Contains(strUniqueNum))
{
Console.WriteLine("{0}值存在重复", strUniqueNum);
Console.ReadKey();
}
list.Add(strUniqueNum);
if (i % == )
{
Console.WriteLine("没有重复,按Enter键往下看");
Console.ReadKey();
}
}
list.Clear();
}
}
/// <summary>
/// 单例模式实现
/// 唯一值由[0-9a-z]组合而成,且生成的每个ID不能重复
/// </summary>
public class CreateID
{
private static CreateID _instance;
private static readonly object syncRoot = new object();
private EHashtable hashtable = new EHashtable();
private string _strXMLURL = string.Empty;
private CreateID()
{
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "");
hashtable.Add("", "a");
hashtable.Add("", "b");
hashtable.Add("", "c");
hashtable.Add("", "d");
hashtable.Add("", "e");
hashtable.Add("", "f");
hashtable.Add("", "g");
hashtable.Add("", "h");
hashtable.Add("", "i");
hashtable.Add("", "j");
hashtable.Add("", "k");
hashtable.Add("", "l");
hashtable.Add("", "m");
hashtable.Add("", "n");
hashtable.Add("", "o");
hashtable.Add("", "p");
hashtable.Add("", "q");
hashtable.Add("", "r");
hashtable.Add("", "s");
hashtable.Add("", "t");
hashtable.Add("", "u");
hashtable.Add("", "v");
hashtable.Add("", "w");
hashtable.Add("", "x");
hashtable.Add("", "y");
hashtable.Add("", "z");
_strXMLURL = System.IO.Path.GetFullPath(@"..\..\") + "XMLs\\record.xml"; }
public static CreateID GetInstance()
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
{
_instance = new CreateID();
}
}
}
return _instance;
}
/// <summary>
/// 创建UniqueID
/// </summary>
/// <returns>UniqueID</returns>
public string CreateUniqueID()
{
long _uniqueid = GetGuidFromXml();
return Convert10To36(_uniqueid);
}
/// <summary>
/// 获取UniqueID总记录,即获取得到的这个ID是第几个ID
/// 更新UniqueID使用的个数,用于下次使用
/// </summary>
/// <returns></returns>
private long GetGuidFromXml()
{
long record = ;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(_strXMLURL);
XmlElement rootNode = xmldoc.DocumentElement;
//此次的个数值
record = Convert.ToInt64(rootNode["record"].InnerText);
//此次的个数值+1 == 下次的个数值
rootNode["record"].InnerText = Convert.ToString(record + );
xmldoc.Save(_strXMLURL);
return record;
}
/// <summary>
/// 10进制转36进制
/// </summary>
/// <param name="intNum10">10进制数</param>
/// <returns></returns>
private string Convert10To36(long intNum10)
{
string strNum36 = string.Empty;
long result = intNum10 / ;
long remain = intNum10 % ;
if (hashtable.ContainsKey(remain.ToString()))
strNum36 = hashtable[remain.ToString()].ToString() + strNum36;
intNum10 = result;
while (intNum10 / != )
{
result = intNum10 / ;
remain = intNum10 % ;
if (hashtable.ContainsKey(remain.ToString()))
strNum36 = hashtable[remain.ToString()].ToString() + strNum36;
intNum10 = result;
}
if (intNum10 > && intNum10 < )
{
if (hashtable.ContainsKey(intNum10.ToString()))
strNum36 = hashtable[intNum10.ToString()].ToString() + strNum36;
}
return strNum36;
}
}
/// <summary>
/// Summary description for EHashTable
/// </summary>
public class EHashtable : Hashtable
{
private ArrayList list = new ArrayList();
public override void Add(object key, object value)
{
base.Add(key, value);
list.Add(key);
}
public override void Clear()
{
base.Clear();
list.Clear();
}
public override void Remove(object key)
{
base.Remove(key);
list.Remove(key);
}
public override ICollection Keys
{
get
{
return list;
}
}
}
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<root>
<record id="record"></record>
</root>

二、在JS中生成GUID,类似.NET中的 Guid.NewGuid(),代码如下:

function newGuid() { //方法一:
var guid = "";
var n = ((( + Math.random()) * 0x10000) | ).toString().substring();
for (var i = ; i <= ; i++) {
guid += n;
}
return guid;
}
function newGuid() { //方法二:
var guid = "";
for (var i = ; i <= ; i++) {
var n = Math.floor(Math.random() * 16.0).toString();
guid += n;
if ((i == ) || (i == ) || (i == ) || (i == ))
guid += "-";
}
return guid;
}

三、在SQL存储过程生成GUID,代码如下:

ALTER PROCEDURE [dbo].[pro_CreateGuid]
@Prefix NVARCHAR(),
@outputV_guid NVARCHAR() OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SET @outputV_guid = @Prefix + REPLACE(CAST(NEWID() AS VARCHAR()),'-','')
END

参考:http://www.jb51.net/article/43823.htm

以下我整理了一份dotnet使用的GUID库:

    /// <summary>
/// Guid生成工具
/// </summary>
public class GuidHelper
{
/// <summary>
/// 由连字符分隔的32位数字
/// </summary>
/// <returns></returns>
private static string GetGuid()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
return guid.ToString();
} /// <summary>
/// 根据GUID获取16位的唯一字符串
/// </summary>
/// <param name=\"guid\"></param>
/// <returns></returns>
public static string GuidTo16String()
{
long i = ;
foreach (byte b in Guid.NewGuid().ToByteArray())
i *= ((int)b + );
return string.Format("{0:x}", i - DateTime.Now.Ticks);
} /// <summary>
/// 根据GUID获取19位的唯一数字序列
/// </summary>
/// <returns></returns>
public static long GuidToLongID()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, );
} /// <summary>
/// 唯一订单号生成
/// </summary>
/// <returns></returns>
public static string GenerateOrderNumber()
{
string strDateTimeNumber = DateTime.Now.ToString("yyyyMMddHHmmssms");
string strRandomResult = NextRandom(, ).ToString();
return strDateTimeNumber + strRandomResult;
} /// <summary>
/// 参考:msdn上的RNGCryptoServiceProvider例子
/// </summary>
/// <param name="numSeeds"></param>
/// <param name="length"></param>
/// <returns></returns>
private static int NextRandom(int numSeeds, int length)
{
// Create a byte array to hold the random value.
byte[] randomNumber = new byte[length];
// Create a new instance of the RNGCryptoServiceProvider.
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
// Fill the array with a random value.
rng.GetBytes(randomNumber);
// Convert the byte to an uint value to make the modulus operation easier.
uint randomResult = 0x0;
for (int i = ; i < length; i++)
{
randomResult |= ((uint)randomNumber[i] << ((length - - i) * ));
}
return (int)(randomResult % numSeeds) + ;
} /// <summary>
/// 生成特定位数的唯一字符串
/// </summary>
/// <param name="num">特定位数</param>
/// <returns></returns>
public static string GenerateUniqueText(int num)
{
string randomResult = string.Empty;
string readyStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rtn = new char[num];
Guid gid = Guid.NewGuid();
var ba = gid.ToByteArray();
for (var i = ; i < num; i++)
{
rtn[i] = readyStr[((ba[i] + ba[num + i]) % )];
}
foreach (char r in rtn)
{
randomResult += r;
}
return randomResult;
}
上一篇:基于visual Studio2013解决C语言竞赛题之0612递归


下一篇:两句话掌握python最难知识点——元类