我正在使用此代码生成唯一代码
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程序也请让我知道
答案 0 :(得分:2)
您创建的密码命名为“sand”,然后在for循环中,您发送相同的密码“num”次。你可以试试这个:
int num;
if ( int.TryParse(ids.Text,out num))
{
for (int i = 1; i <= num; i++)
{
var sand = CreateRandomPassword();