且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何自动生成用户ID?

更新时间:2022-10-14 23:27:17

从不填写文本框:只应在数据为时分配值致力于DB。如果您在此之前尝试做出决定,则只要您开始在多用户环境中工作,就会出现间歇性问题,因为两个站最终会尝试使用相同的用户ID。如果你没有发现它,这会严重损害你的数据库完整性,你会遇到真正的问题。

并考虑一下:为什么用户想要知道他的用户ID是什么在他真正报名之前?只有在他是正式会员之后,它才与任何人相关。



因此,jgakenhe说:在数据库中使用IDENTITY字段来分配唯一的ID号,并格式化它们以C#或SQL显示:

  string  ID =  string  .Format(  AA {0:D3},idValueFromDB); 



  SELECT  '  AA' +  RIGHT '  000' + CAST(IdValue  AS   NVARCHAR  3 )), 3  AS  ID  FROM  MyTable 


您可以使用主键标识TY

I need to generate automatic userid with sting AA at first, but i dont know how?
for example
AA001
AA002
...
it will be automaticaly filled in textbox when user input their personal data, can anybody help me?

i used code like this

MsUser g = new MsUser();
            g.UserID = textBox1.Text;
            g.UserName = textBox2.Text;
            g.UserEmail = textBox4.Text;
            g.UserAddress = richTextBox1.Text;
            g.UserPhone = textBox5.Text;
            g.UserRole = comboBox1.Text;
            db.MsUsers.AddObject(g);
            db.SaveChanges();
            refresh();

Never "fill in" a textbox: the value should only be assigned when the data is committed to the DB. If you try to decide before that point, as soon as you start working in a multiuser environment you will get intermittent problems as two stations end up trying to use the same userID. If you don't spot it, this can seriously compromise your database integrity, and you will have real problems.
And think about it: why the heck would a user want to know what his userID is going to be before he actually signs up? It's only relevant to anyone after he is a "full member".

So as jgakenhe said: use a IDENTITY field at the DB to allocate unique id numbers, and format them to display in C# or SQL:
string ID = string.Format("AA{0:D3}", idValueFromDB);


SELECT 'AA' + RIGHT('000' + CAST(IdValue AS NVARCHAR(3)),3) AS ID FROM MyTable


you can use primary key identity