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("密码已成功生成!");
}
}
}
小程序运行结果: