Reputation: 3120
I have an application where I need to store a value in a column. The value is a string in the code and the column data type is nvarchar
.
foreach (DataRow row in dt.Rows)
{
//Generate a random length for randomKey range between 3 and 6 characters
Random randKey = new Random();
int randKeyLength = randKey.Next(3, 6);
//calculate randomKeyString
String randomKeyString = md5Prepare.gen_randomKeyString(randKeyLength);
//add randomKeyString to database
row["randomKey"] = randomKeyString;
}
When I check the database, the column "randomKey" is unchanged. What is wrong here?
Upvotes: 1
Views: 1445
Reputation: 28345
You didn't call any Commit methods on DataRow
or DataTable
.
You need the DataAdapter
and DataSet
to actually update database.
foreach (...)
{
// your code here
}
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Update(dataSet);
Upvotes: 1
Reputation: 5083
Do not create the instance of the Random object inside the foreach: Rather create it before.
The sequence of random numbers generated by a single Random instance is supposed to be uniformly distributed. By creating a new Random instance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.
For the sake of completeness, if you really need to reseed a Random, you'll create a new instance of Random with the new seed:
rnd = new Random(newSeed);
Thanks to Mehrdad Afshari
Upvotes: 0
Reputation: 1026
There is nothing wrong with what you are doing to set the value. Strings are unicode in C# as is nvarchar. You simply need to write the values back/insert them into the database as what you are doing at the moment is manipulating the in memory representations of what you have read from the database.
Upvotes: 0