【发布时间】:2016-04-06 08:31:59
【问题描述】:
我正在使用此代码生成唯一代码
public static string CreateRandomPassword()
{
string _allowedChars = "1234567899999";
Random randNum = new Random((int)DateTime.Now.Ticks);
char[] chars = new char[5];
for (int i = 0; i < 5; i++)
{
chars[i] = _allowedChars[randNum.Next(_allowedChars.Length)];
//No need to over complicate this, passing an integer value to Random.Next will "Return a nonnegative random number less than the specified maximum."
}
return new string(chars);
这用于向 sql 表发送条目。 ids 是我在其中输入要生成多少个唯一代码的文本框
protected void Button1_Click(object sender, EventArgs e)
{
var sand = CreateRandomPassword();
int num;
if ( int.TryParse(ids.Text,out num))
{
for (int i = 1; i <= num; i++)
{
string strcon = ConfigurationManager.ConnectionStrings["slxserv"].ToString();
using (SqlConnection con = new SqlConnection(strcon))
using (SqlCommand cmd = new SqlCommand("INSERT INTO passwords (password) VALUES (@password) "))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@password",sand);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
当我尝试生成多个唯一代码时,请帮助我,它会多次使用相同的代码将数据发送到 sql。我做错了什么请告诉我。或者也可以用sql程序做也请告诉我
【问题讨论】:
-
这段代码有很多问题——你只创建了一个单个密码,循环调用
cmd.Parameters.AddWithValue("@password",sand);实际上添加了new参数,打开/关闭循环内的连接只会浪费CPU。最糟糕的问题是CreateRandomPassword本身。首先,.NET 已经有了生成强密码的方法,如here 所示。其次,密码非常非常弱,9s 比其他数字更频繁 -
查看this post.接受的答案