asp.net method for generating unique random codes

  • 2020-05-10 17:59:13
  • OfStack

1. Write your own code to generate a random combination of Numbers and letters. Every time you generate one, go to the database to check whether the random code exists or not.
Advantages: I didn't find any advantages.
Disadvantages: the production speed is slow, but also query the database, when the data is large, may repeat the probability will be higher, to query the database for many times.

2. guid, this method should be used more often.
Advantages: easy to use, no need to write extra code
Cons: relatively large database footprint, especially slow queries based on guid (it's a string, after all).

3. Primary key + random code, the generated random code saved to the database must have a primary key, with the primary key + random characters to combine. Production steps:
1) get id from the id generator first, for example, 155.
2) fill in the string with fixed digits (such as 8 bits) (fill in 0 to the left of the insufficient digits, and use the number directly beyond the digits), and get: 00000155
3) in each randomly inserted into the Numbers behind a letter, or other non-numeric symbols, are: 0 A0F0R0Y0H1K5L5M
You get a random invitation code with only one.
Advantage: the use is also relatively simple, do not need to query the database. The biggest advantage is that when querying, you can directly get the primary key id according to the invitation code.
Then according to id to the database query (very fast), and then compare the query out of the invitation code and the user submitted the invitation code whether 1.
Cons: you need to use the id generator, which is hard to use if the primary key is self-growing (you need to insert the database to get id, and then update the invitation code).

4. Sometimes the product manager says, "I want all the invitation codes to be digital." why? no why? I like it. *(&^ ^(^%&^$&^$) *(&^ ^ ^%&^$&^$).
1) get id: 155
2) convert to base 8:233
3) to a string, followed by the '9' character: 2339
4) a number of random numeric characters are generated randomly: 2003967524987
When you convert to base 8, you don't have the character 9, and then you add a '9' after it, so you can determine the uniqueness. And then you can just generate a bunch of random Numbers.
Advantages and disadvantages the same method 3

Currently, method 3 and method 4 are all used in our products, and it feels ok.

PS: this is a simple idea. If you have a better idea, please share. ^_^
[author] : BearRui(AK-47)
[blog] : http: / / www cnblogs. com/BearsTaR /

Related articles: