当前位置:   article > 正文

C#之Win form小程序——生成8位数字和大小写字母组合的随机数并插入SQL Server数据库中_c# 随机生成8位密码

c# 随机生成8位密码

C#刚学习的新手,好多都不是很懂。感觉做出来,看到实现的结果还蛮开心的!

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Data.SqlClient;
  11. namespace LocalRandomPassword
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. //生成密码组合
  20. private static char[] constant =
  21. {
  22. '0','1','2','3','4','5','6','7','8','9',
  23. 'a','b','c','d','e','f','g','h','i','j','k','p','q','r','s','t','u','v','w','x','y','z',
  24. 'A','B','C','D','E','F','G','H','I','J','K','P','Q','R','S','T','U','V','W','X','Y','Z'
  25. };
  26. /// <summary>
  27. /// 获取随机长度的密码
  28. /// </summary>
  29. /// <param name="Length">密码长度</param>
  30. /// <returns></returns>
  31. //生成随即密码长度
  32. public static string GenerateRandom(int Length)
  33. {
  34. System.Text.StringBuilder newRandom = new System.Text.StringBuilder(54);
  35. Random rd = new Random();
  36. for (int i = 0; i < Length; i++)
  37. {
  38. newRandom.Append(constant[rd.Next(54)]);
  39. }
  40. return newRandom.ToString();
  41. }
  42. protected void button1_Click(object sender, EventArgs e)
  43. {
  44. SqlConnection cn = new SqlConnection();
  45. cn.ConnectionString = "Data Source=.;database=RandomPassword;integrated security=SSPI";
  46. cn.Open();
  47. for(int i=0;i<10;i++)
  48. {
  49. //调用方法获得随机数
  50. string str = GenerateRandom(8);//“8”是随机数的位数。
  51. //后边添加到数据库
  52. //将str添加到数据库。
  53. string sql = "insert into T_Password(Password) values('" + str + "')";
  54. SqlCommand cmd = new SqlCommand(sql,cn);
  55. cmd.ExecuteNonQuery();
  56. }
  57. cn.Close();
  58. MessageBox.Show("密码已成功生成!");
  59. }
  60. }
  61. }

小程序运行结果:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/169867
推荐阅读
相关标签
  

闽ICP备14008679号