如何编写一个方法来生成随机/唯一字符串,然后如何调用该方法?

Jiale Xue - MSFT 33,686 信誉分 Microsoft 供应商
2024-04-23T08:26:19.93+00:00

我将创建一个按钮,让用户为他/她自己的记录生成一个唯一的字符串。

我应该如何编写方法以及如何调用它?

谢谢。

        private void buttonInsertString_Click(object sender, EventArgs e)
        {
//When user clicks the button, the program will generate a unique string for his/her own record.


                using (OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString))
                {
                    OdbcCommand cmd = new OdbcCommand("INSERT into TableUser (GeneratedUniqueString) Values ('" + ..... + "')  WHERE Username ='" + Environment.UserName + "'", Cn);

                    //if the connection is not already open - then open it
                    if (Cn.State != ConnectionState.Open)
                    {
                        Cn.Open();
                    }

                    cmd.ExecuteNonQuery();

                }


        }


        public static void GenerateRandomUniqueString()
        {
//How to write a method to gerate a unique string (lowcase a-z letter only; lenth: 5)? Unique means: the generated string cannot be the one already in Database TableUser field GeneratedUniqueString. So there should be two steps: 1) generate a random 5 character string, lower case letter only; 2) check if the string is in database, if yes, regenerate a random string until it is not in the database.


        }

Note:此问题总结整理于: How to write a method to generate random/unique string, then how to call the method?

Windows 窗体
Windows 窗体
一组用于开发图形用户界面的 .NET Framework 托管库。
82 个问题
C#
C#
一种面向对象的类型安全的编程语言,它起源于 C 语言系列,包括对面向组件的编程的支持。
106 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Hui Liu-MSFT 40,266 信誉分 Microsoft 供应商
    2024-04-24T06:49:01.6333333+00:00

    尝试使用 GUID:

    string uniqueString =  System.Guid.NewGuid().ToString();  
    

    你甚至不必使用方法。

    另外,最好不要像这样拼接 SQL,而是使用参数:

    cmd.CommandText = "SELECT * FROM t1 WHERE id = ?";  
    cmd.Parameters.Add("@id", OdbcType.Int).Value = 4;  
    

    更新: GUID 的全名是全局唯一标识符, 其长度和格式是固定的,32 个十六进制数字分组成 8-4-4-4-12 块,例如:

    dfa8492b-4a88-4ec3-b675-b50bd78a9876  
    

    这意味着它有2^128个数字,这是一个巨大的数字,比宇宙中观测到的恒星还要多,所以从中得到两个数字并且恰好相同的概率无限接近0,在大多数情况下可以满足对随机数的要求。

    但重复的概率毕竟不是0。如果您仍然担心重复,可以添加验证以确定它是否已经存在。或者在最后再添加一个 GUID 或时间戳,这仍然不能保证概率为 0,但会让速率继续缩小。

    Update2: 根据您的要求,使用 RNGCryptoServiceProvider 可能是一个好主意:

            public static string RandomString(int length)  
            {  
                string valid = "abcdefghijklmnopqrstuvwxyz";  
                StringBuilder sb = new StringBuilder();  
                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())  
                {  
                    byte[] uintBuffer = new byte[sizeof(uint)];  
      
                    while (length-- > 0)  
                    {  
                        rng.GetBytes(uintBuffer);  
                        uint num = BitConverter.ToUInt32(uintBuffer, 0);  
                        sb.Append(valid[(int)(num % (uint)valid.Length)]);  
                    }  
                }  
                return sb.ToString();  
            }  
    

    但是您仍然需要考虑重复的可能性并处理它。

    Update3: 我认为最好不要更改 RandomString 方法。 请尝试如下操作:

           static void Main(string[] args)  
            {  
                string connString = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\test\db\test.mdb;";  
                using (OdbcConnection Cn = new OdbcConnection(connString))  
                {  
                    using (OdbcCommand cmd = new OdbcCommand())  
                    {  
                        if (Cn.State != ConnectionState.Open)  
                        {  
                            Cn.Open();  
                        }  
                        string randomString = getUniStr();  
                       
                        cmd.CommandText = "insert into TableUser .....";  
                        cmd.Parameters.AddWithValue("", OdbcType.VarChar).Value = randomString;  
                        cmd.ExecuteNonQuery();  
                    }  
                }  
                Console.WriteLine("Press any key to continue...");  
                Console.ReadLine();  
            }  
            public static string getUniStr()   
            {  
                string connString = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\test\db\test.mdb;";  
                using (OdbcConnection Cn = new OdbcConnection(connString))  
                {  
                    using (OdbcCommand cmd = new OdbcCommand())  
                    {  
                        if (Cn.State != ConnectionState.Open)  
                        {  
                            Cn.Open();  
                        }  
                        int count;  
                        string randomString = RandomString(5);  
                        do  
                        {  
                            cmd.Connection = Cn;  
                            cmd.CommandText = "select count(*) from table2 where ID=?";  
                            //If there is only one line in the code block, the braces can be omitted.  
                            if (cmd.Parameters.Contains("ID"))  
                                cmd.Parameters["ID"].Value = randomString;  
                            else  
                                cmd.Parameters.AddWithValue("ID", OdbcType.VarChar).Value = randomString;  
                            count = int.Parse(cmd.ExecuteScalar().ToString());  
                            if (count != 0)  
                                randomString = RandomString(5);  
                        }  
                        while (count == 1);  
                        return randomString;  
                    }  
                }  
            }  
    

    如果回复有帮助,请点击“接受答案”并点赞。 注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。

    1 个人认为此答案很有帮助。
    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助