[英]string to varchar C# / SQL Server
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
. 该值是代码中的字符串,列数据类型为
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. 当我检查数据库时,列“ randomKey”不变。 What is wrong here?
怎么了
You didn't call any Commit methods on DataRow
or DataTable
. 您没有在
DataRow
或DataTable
上调用任何Commit方法。
You need the DataAdapter
and DataSet
to actually update database. 您需要
DataAdapter
和DataSet
才能实际更新数据库。
foreach (...)
{
// your code here
}
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Update(dataSet);
There is nothing wrong with what you are doing to set the value. 设置值没有错。 Strings are unicode in C# as is nvarchar.
字符串与nvarchar在C#中是unicode。 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.
您只需要将这些值写回/将其插入数据库中,就如同当前正在操作从数据库中读取的内存中表示形式一样。
Do not create the instance of the Random object inside the foreach: Rather create it before. 不要在foreach内部创建Random对象的实例:而是在之前创建它。
The sequence of random numbers generated by a single Random instance is supposed to be uniformly distributed. 由单个Random实例生成的随机数序列应该是均匀分布的。 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.
通过快速连续地为每个随机数创建一个新的Random实例,您很可能使用相同的值为它们播种并让它们生成相同的随机数。 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: 为了完整起见,如果您确实需要重新设定Random的种子,则将使用新种子创建一个Random的新实例:
rnd = new Random(newSeed);
Thanks to Mehrdad Afshari 感谢Mehrdad Afshari
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.