如何在Coldfusion中创建随机字符串时检查重复值?

fre*_*ent 1 random coldfusion loops duplicates while-loop

我正在运行Coldfusion8/MySQL 5.0.88并拥有带有id的表,这是随机字符串az 0-9

我想在表中创建新记录时避免重复条目,但我不确定如何正确设置它.

这是我有的:

<cfset variables.listOfAppIds = "">

<!--- get all ids --->
<cfquery datasource="db" name="app_ids">
    SELECT app_id FROM apps
</cfquery>

<!--- create comma-separated list --->
<cfloop query="app_ids">
    <cfset variables.listOfAppIds = variables.listOfAppIds & "," & app_ids.app_id>
</cfloop>

<!--- create random string and test if it is in listOfAppIds --->
<cfloop condition="#ListFindNoCase(variables.listOfAppIds, variables.rndString, ',')#">
    <cfset variables.stringLength = 10>
    <cfset variables.stringList = "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">
    <cfset variables.rndString = "">
    <cfloop from="1" to="#variables.stringLength#" index="i">
        <cfset variables.rndNum = RandRange(1, listlen(variables.stringList))>
        <cfset variables.rndString = variables.rndString & listGetAt(variables.stringlist, variables.rndNum)>
    </cfloop>
    <cfset variables.current_appId = variables.rndString>
</cfloop>
Run Code Online (Sandbox Code Playgroud)

问题:
我不确定我while-loop是否使用正确.这会确保没有找到重复项吗?

感谢帮助!

bar*_*nyr 5

我会重新考虑这种方法.您可以使用GUID,然后根本不检查(许多应用程序都这样做).

或者创建新的随机ID,然后查询数据库以查看是否发生了冲突.这样数据库就可以为您处理相同的逻辑.那么你的逻辑就是:

collision=true;
while (collision=true) {
    newID=RandomIdFunction();
    SELECT app_id FROM apps where app_id = newID;
    if query had no rows, set collision=false;
}
Run Code Online (Sandbox Code Playgroud)

随着数据库填满碰撞的可能性,这将变慢,这就是为什么我可能会使用GUID方法.

  • 随机!=独特.如果在URL中使用这些值,那么它们基本上是公共值,那么有没有理由不使用简单的递增计数器? (2认同)