【问题标题】:I am trying to generate numaric unique code and send it to sql server我正在尝试生成数字唯一代码并将其发送到 sql server
【发布时间】: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.接受的答案

标签: sql-server-2008 c#-4.0


【解决方案1】:

您创建的密码命名为“sand”,然后在 for 循环中,您发送相同的密码“num”次。你能试试这个吗:

    int num; 
    if ( int.TryParse(ids.Text,out num))
    {
        for (int i = 1; i <= num; i++)
        {
           var sand = CreateRandomPassword();

【讨论】:

  • 进行此更改后结果相同
猜你喜欢
  • 1970-01-01
  • 2020-06-21
  • 2014-07-20
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多