最有效的方法...唯一的随机字符串 [英] Most Efficient Way to... Unique Random String
问题描述
我需要efficently插入5个字符的随机字符串到数据库中,同时确保它是独一无二的。生成随机字符串是没有问题的,但是目前我在做什么正在生成的字符串,然后检查数据库,如果它已经存在......如果是这样,我开始了。
有没有更有效的方法来做到这一点的过程?
请注意,我不想使用GUID或其他任何超过5个字符....我一定要坚持5个字符。
PS:我不认为它的确与众不同,但我的琴弦都是区分大小写
。下面是随机字符串部分。
公共功能GetRandomNumbers(BYVAL numChars个为整数)作为字符串
昏暗的字符作为字符串()= {_
A,B,C,D,E,F,_
G,H,I,J,K,L,_
M,N,O,P,Q,R,_
的S,T,U,V,W,X,_
Y,Z,0,1,2,3,_
4,5,6,7,8,9,_
一,B,C,D,E,F,_
G,H,I,J,K,升,_
M,N,O,P,Q,R,_
S,T,U,V,W,×,_
Y,Z}
DIM RND作为新的随机()
随机暗淡作为字符串=的String.Empty
昏暗我为整数= 0
虽然我< numChars个
随机+ =字符(RND。[下一页](0,62))
System.Math.Max(System.Threading.Interlocked.Increment(ⅰ)中,i - 1)
虽然结束
返回随机
结束功能
与按顺序添加(所以他们是唯一的)5个字符的字符串的一个大池创建一个表,并有一个GUID作为主键。添加一列,表明他们是否使用与否。
当你需要一个新的号码,你从池中的GUID选择顶部1,为了(因此它成为随机),并设置结果为花。
I need to efficently insert a 5 character RANDOM string into a database while also ensuring that it is UNIQUE. Generating the random string is not the problem, but currently what I am doing is generating the string and then checking the DB if it exists already... if it does, I start over.
Is there a more efficient way to do this process?
Please note, I do NOT want to use GUID or anything else that is more than 5 Characters.... I MUST stick to 5 Characters.
PS: I don't think it makes a difference, but my strings are all case sensitive.
Here is the "Random String" portion
Public Function GetRandomNumbers(ByVal numChars As Integer) As String
Dim chars As String() = { _
"A", "B", "C", "D", "E", "F", _
"G", "H", "I", "J", "K", "L", _
"M", "N", "O", "P", "Q", "R", _
"S", "T", "U", "V", "W", "X", _
"Y", "Z", "0", "1", "2", "3", _
"4", "5", "6", "7", "8", "9", _
"a", "b", "c", "d", "e", "f", _
"g", "h", "i", "j", "k", "l", _
"m", "n", "o", "p", "q", "r", _
"s", "t", "u", "v", "w", "x", _
"y", "z"}
Dim rnd As New Random()
Dim random As String = String.Empty
Dim i As Integer = 0
While i < numChars
random += chars(rnd.[Next](0, 62))
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Return random
End Function
Create a table with a big pool of 5-character strings that are added in sequence (so they are unique), and have a GUID as their primary key. Add a column to indicate whether they are used or not.
When you need a new number, you select top 1 from the pool, order by the guid (so it becomes random), and set the result as "spent".
这篇关于最有效的方法...唯一的随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!