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

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LocalRandomPassword
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        //生成密码组合
        private static char[] constant =   
          {   
            '0','1','2','3','4','5','6','7','8','9',   
            'a','b','c','d','e','f','g','h','i','j','k','p','q','r','s','t','u','v','w','x','y','z',   
            'A','B','C','D','E','F','G','H','I','J','K','P','Q','R','S','T','U','V','W','X','Y','Z'   
          };
        /// <summary>
        /// 获取随机长度的密码
        /// </summary>
        /// <param name="Length">密码长度</param>
        /// <returns></returns>
        //生成随即密码长度
        public static string GenerateRandom(int Length)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(54);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(54)]);
            }
            return newRandom.ToString();
         }

   protected void button1_Click(object sender, EventArgs e)
    { 
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "Data Source=.;database=RandomPassword;integrated security=SSPI";
        cn.Open();
        for(int i=0;i<10;i++)
        {
            //调用方法获得随机数
            string str = GenerateRandom(8);//“8”是随机数的位数。
              //后边添加到数据库
              //将str添加到数据库。
            string sql = "insert into T_Password(Password) values('" + str + "')";
            SqlCommand cmd = new SqlCommand(sql,cn);
            cmd.ExecuteNonQuery();
         } 
        cn.Close();
        MessageBox.Show("密码已成功生成!");
    } 
  }
}

小程序运行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值