最适合为用户生成ID [英] best for to generate id for user

查看:117
本文介绍了最适合为用户生成ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我用这段代码为每条记录生成ID,将其存储在db中,并在我的win-form应用程序中将其显示给用户:

 私有 静态  int  getID()
 {
// 从文件中读取新ID并将其返回
            //  100是基本ID 
             int  id;
            如果(File.Exists(" ))
            {
                TextReader tr =  StreamReader(" );
                id =  Int32  .Parse(tr.ReadLine());
                id ++;
                tr.Close();
                File.WriteAllText( @"  string  .Empty);
                TextWriter tw =  StreamWriter(" );
                tw.WriteLine(id);
                tw.Close();
            }
            其他
            {
                id =  100 ;
                TextWriter tw =  StreamWriter(" );
                tw.WriteLine(id);
                tw.Close();
            }
            返回 ID;
} 


这是个好方法吗?
最好的方法是什么?

解决方案

不好的坏方法.它在单用户环境中存在问题,不用管多用户环境.

问题在于文件不应该被多个人同时打开,因此必须将它们锁定-如果文件被锁定,则无法打开它.另外,如果其他任务介于读取和写入之间,则它可能已经使用了该编号.

如果需要整数ID,请尝试使用ID字段设置为Identity的数据库,数据库系统将自动为您创建ID.或者,如果您不打算告诉用户其ID是什么(他们可能不需要知道),为什么不改用Guid?


hi iuse this piece of code to generate the id for every record.store it in db and show it to the user in my win-form application :

 private static int getID()
 {
	    //read new id from file and return it 
            // 100 is Base id
            int id;
            if (File.Exists("id.txt"))
            {
                TextReader tr = new StreamReader("id.txt");
                id = Int32.Parse(tr.ReadLine());
                id++;
                tr.Close();
                File.WriteAllText(@"id.txt", string.Empty);
                TextWriter tw = new StreamWriter("id.txt");
                tw.WriteLine(id);
                tw.Close();
            }
            else
            {
                id = 100;
                TextWriter tw = new StreamWriter("id.txt");
                tw.WriteLine(id);
                tw.Close();
            }
            return id;
}


is it a good way or not?
what is the best way?

解决方案

Bad, bad way. it has problems in single user, never mind a multiuser environment.

The problem is that files are not meant to be opened by multiple people at the same time, so they have to be locked - and if a file is locked, you can''t open it. Plus, if some other task gets in between the read and the write, it could use that number already.

If you want integer IDs, then try using a database, with the ID field set to Identity, and the database system will create the ID for you automatically. Or, if you are not planning on telling your user what their ID is (and they probably don''t need to know) why not use a Guid instead?


这篇关于最适合为用户生成ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆