Now the web will often need to generate some invitation code, activation code. The need is unique and random. Here's a summary of some common methods for generating random code and sharing your own 1 methods.
1. Write your own code to generate random numbers and combinations of letters , every 1 to go to the database query whether the random code already exists, if already exist, then again, until not repeat.
Advantages: no advantage found.
Disadvantages: Slow production, but also to query the database, when the amount of data, the likelihood of repetition will be relatively high, to query multiple databases.
2. Guid, this method should be used more .
Advantages: Easy to use without writing extra code yourself
Disadvantage: Occupy a relatively large database space, especially based on the GUID query speed slower (after all, a string).
3. Primary key + Random code way, we generated a random code saved to the database will certainly have a primary key, with the primary key + random character combination. Production steps:
1 first get the ID from the ID generator, for example, 155.
2 fill in a fixed number of digits (such as 8-bit) of the string (not enough digits left to fill 0, more than the number of digits directly using the number), get: 00000155
3 randomly insert 1 letters or other non-numeric symbols after each number, and get: 0a0f0r0y0h1k5l5m
This allows you to get 1 random, unique invitation codes.
Advantages: Use is also relatively simple, do not 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 the ID to the database query (fast), and then compare the query out of the invitation code and the user submitted the invitation code is consistent.
Disadvantage: Need to use the ID generator, if the primary key is the database from the growth is not very good (need to insert the database to get ID, and then update the invitation code). Sometimes the product manager says, I want the invitation code to be digital. Why No why? I like it. * (&^ ^%&^&^&^ The Method 3 can be adapted to achieve the only pure digital random code.
1) Get id:155
2) Convert to 8:233
3) to string, and add ' 9 ' character in the back: 2339
4 randomly produces several random digit characters at the back: 2003967524987
When you move to 8, you don't get the 9 character and then add a ' 9 ' to the back so you can determine uniqueness. Finally, some random numbers will be generated behind.
Advantages and Disadvantages Same Method 3
At present the method 3,4 method is used in our product, the feeling is also OK.
PS: The above is personal humble opinion, have a better way of the students please share under. ^_^
[Author]:bearrui (AK-47)
[Blog]: [http://www.cnblogs.com/BearsTaR/]