首页 > 解决方案 > 如何创建将字母分配给特定单词的密码?

问题描述

如何在 C# 中创建简单的密码应用程序,我将字母分配给特定的单词,例如t将表示单词take,所以t将是密码代码和take描述,这些密码可以存储在数据库或文本文件中?

我在下面尝试过这段代码,但不适用于密码

private void pictureBox5_Click_1(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-EU4PTNQ;Initial Catalog=Medrive;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
    {
       con.Open();
              
       if (bunifuTextBox2.Text != "")
       {
           string DescriptionQueryStr = "Select CName from Ciphers";
    
           using (SqlCommand cmd = new SqlCommand(DescriptionQueryStr, con))
           {
                        
               string[] tbVals = bunifuTextBox2.Text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
               for (int i = 0; i < tbVals.Length; i++)
               {
                   DescriptionQueryStr = "where Description=@Description" + i.ToString() + "OR";
                   cmd.Parameters.Add("@Description" + i.ToString(), SqlDbType.VarChar).Value = tbVals[i];
               }
               //Strip off the last OR
               DescriptionQueryStr = DescriptionQueryStr.Substring(0, DescriptionQueryStr.Length - 2);
               StringBuilder sb = new StringBuilder();

               using (SqlDataReader da = cmd.ExecuteReader())
               {
                   if (da.Read())
                   {
                       var hasAnotherRecord = true;
                       while (hasAnotherRecord)
                       {
                           sb.AppendLine(da.GetValue(0).ToString());
                           hasAnotherRecord = da.Read();
  
                           if (hasAnotherRecord )
                              sb.Append('-');
                        }
                    }
                }
 
                TAbunifuTextBox10.Text = sb.ToString();
                System.Diagnostics.Debug.Write("Hello via Debug!");
            }                   
        }
    }
}

标签: c#

解决方案


您没有将查询条件 ( WHERE ...) 添加到发送到服务器的实际查询中。

您正在构建您的命令,例如

SqlCommand cmd = new SqlCommand(DescriptionQueryStr, conn);

但是您永远不会cmd.CommandText再次更改(保存发送到 sql 服务器的查询的属性)。因此,发送到您的服务器的查询Select CName from Ciphers将返回所有行。

在您的for循环中,您正在更改DescriptionQueryStr,但这些更改永远不会在cmd.CommandText. 此外,您也没有正确处理条件,因为不是将每个新条件附加到DescriptionQueryStr,而是在循环的每次迭代中替换它。

//Concat all conditions in a String builder
StringBuilder conditions = new StringBuilder();
for (int i = 0; i < tbVals.Length; i++) {
    //if there is more than one condition, add an OR inbetween them
    if (i > 0) conditions.Append(" OR ");  
    conditions.Append($"Description = @Description_{i}");
    cmd.Parameters.Add("@Description_{i}", SqlDbType.VarChar).Value = tbVals[i];
}

//If there is at least one parameter, add the conditions to the query
if (tbVals.Length > 0)
    cmd.CommandText += $" WHERE {conditions.ToString()}";

推荐阅读