question

VAer-4038 avatar image
0 Votes"
VAer-4038 asked ·

How to write a method to generate random/unique string, then how to call the method?

I will create a button and let user to generate a unique string for his/her own record.

How should I write the method and how to call it?

Thanks.

         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.
    
    
         }
dotnet-csharpwindows-forms
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered ·

Try to use GUID:

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

You don't even have to use a method.

In addition, it is best not to splice SQL like this, but use parameters:

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

Update:
The full name of GUID is globally unique identifier,
Its length and format are fixed, 32 hex digits grouped into chunks of 8-4-4-4-12, for example:

 dfa8492b-4a88-4ec3-b675-b50bd78a9876

This means that it has 2^128 numbers, which is a huge number, more than the stars in the universe have been observed, so the probability of getting two numbers from it and it happens to be the same is infinitely close to 0, which can meet the requirements for random numbers in most cases.

But the probability of repetition is not 0 after all. If you are still worried about repetition, you can add a verification to determine whether it already exists. Or add another GUID or timestamp at the end, which still does not guarantee that the probability is 0, but it will make the rate continue to shrink.

Update2:
Depending on your requirements, using RNGCryptoServiceProvider may be a good idea:

         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();
         }

But you still need to consider the possibility of duplication and deal with it.

Update3:
I think it is better not to change the RandomString method.
Please try something like this:

        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;
                 }
             }
         }

If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 14 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

What is GUID? How can it guaranteed it is unique? How can I define string length? If John runs the application today and generate a string and that string saved in database table; then Jennifer runs the application tomorrow and generate another string, how can it guaranteed that Jennifer's string is different from John's string?

Thanks.

0 Votes 0 ·

@VAer-4038
I added some explanations, please check it.

0 Votes 0 ·

Thanks, but that is not what I need, I only need length of 5 characters or 6 characters, lower case letter only, as mentioned in the post.

Edit: I make another thread how-to-get-first-recordor-random-record-from-table.html, and try to make the issue easier.


0 Votes 0 ·
Show more comments

Thanks much!

0 Votes 0 ·