-1

I am trying to populate a column in a database with unique strings. How do I achieve this?

My current code just calls the same instance of the GetUniqueKey() method so it just generates the same key. This method will only be run once. Like I said, I am trying to generate a unique key for each row. The GetUniqueKey() method generates an alphanumeric string. How do I calla new instance of Hash.GetUniqueKey() in order to get a new unique key?

private readonly int KEY_SIZE = 5;

public void Fill() {
    connectionStringBuilder.InitialCatalog = "parts";
    connection.ConnectionString = CONSTANTS.connStringParts;

    string query = @"UPDATE parts SET [InternalID] = '" + Hash.GetUniqueKey(KEY_SIZE) + "'";
    SqlCommand command = new SqlCommand(query, connection);
    using(connection) {

        try {
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
        catch(Exception ex) {
            MessageBox.Show(Resource1.DatabaseConnectionError, Resource1.Error, MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}
GBouffard
  • 1,125
  • 4
  • 11
  • 24
kryz
  • 79
  • 11

1 Answers1

0

Did you consider to use Guid?

https://learn.microsoft.com/tr-tr/dotnet/api/system.guid.newguid?view=netframework-4.8

// Create and display the value of two GUIDs.
Guid g = Guid.NewGuid();
Console.WriteLine(g);
Console.WriteLine(Guid.NewGuid());

// This code example produces a result similar to the following:

// 0f8fad5b-d9cb-469f-a165-70867728950e
// 7c9e6679-7425-40de-944b-e07fc1f90ae7
anilcemsimsek
  • 803
  • 10
  • 21
  • The problem is, that will still call the same instance of NewGuid() so it will generate the same GUID. Interesting though. I will consider that as an alternative to my `GetUniqueKey()` method – kryz Apr 22 '20 at 15:27
  • No, it is so so hard to possible of generate same GUID. Check this post https://stackoverflow.com/questions/39771/is-a-guid-unique-100-of-the-time – anilcemsimsek Apr 22 '20 at 15:53
  • Perhaps I am implementing it wrong but when using `string query = @"UPDATE parts SET [InternalID] = '" + Guid.NewGuid() + "'";`, my result is the same key for each row. See: http://prntscr.com/s43cd9 – kryz Apr 22 '20 at 16:08
  • Oouuv i got it. use this sql for update :) UPDATE parts SET [InternalID] = NEWID() – anilcemsimsek Apr 22 '20 at 16:26
  • I couldn't quite figure it out so I followed this thread and created a new table, then merged the tables https://stackoverflow.com/questions/1746125/update-columns-values-with-column-of-another-table-based-on-condition – kryz Apr 22 '20 at 17:27