开发者

how to generate unique id per user?

I have a web开发者_如何学JAVApage Default.aspx which generate the id for each new user after that the id will be subbmitted to database on button click on Default.aspx...

if onother user is also entering the same time the id will be the same ... till they press button on default.aspx

How to get rid of this issue...so that ... each user will be alloted the unique id ...

i m using the read write code to generate unique id ..


You could use a Guid as ids. And to generate an unique id:

Guid id = Guid.NewGuid();

Another possibility is to use an automatically incremented primary column in the database so that it is the database that generates the unique identifiers.


Three options

  1. Use a GUID: Guid.NewGuid() will generate unique GUIDs. GUIDs are, of course, much longer than an integer.

  2. Use intelocked operations to increment a shared counter. Interlocked.Increment is thread safe. This will only work if all the requests happen in the same AppDomain: either process cycling on a refresh of the code will create a new AppDomain and restart the count.

  3. Use an IDENTITY column in the database. The database is designed to handle this, within the request that inserts the new row, use SCOPE_IDENTITY to select the value of the identity to update in memory data (ORMs should handle this for you). (This is SQL Server, other databases have equivalent functionality.)

Of there #3 is almost certainly best.


You could generate a Guid:

Guid.NewGuid()

Or you could let the database generate it for you upon insert. One way to do this is via a Sequence. See the wikipedia article for Surrogate Keys

From the article:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

The Sequence/auto-incremented column option is going to be simpler, and easier to remember when manually querying your DB (during debugging), but the DBA at my work says he's gotten 20% increases in performance by switching to Guids. He was using Oracle, and his database was huge, though :)


I use a utility static method to generate id's, basically use the full datetime(including seconds) and generate a random number of say 3 or 4 characters and return the whole thing, then you can save it to the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜