有没有办法检查数据库中是否存在随机生成的数字? C#

Is there a way to check if random Generated Number existed in database? C#

我有这个自动 LRN 生成数字仅由 12 个数字组成首先我设置 "number" = 100000000000 + 随机数所以输出示例 100569815234 然后该数字将检查它是否已经存在于我的数据库中如果不存在该号码将用于注册学生。但是如果它已经存在于数据库中我有另一个生成的随机数与第一个随机数相同但我如何再次检查它是否已经存在于数据库中?

这是我的代码

里面form2_load*

        Random rnd = new Random(); //
        long firstLRN = rnd.Next(1000000000);
        long addLRN = 100000000000 + firstLRN;
        string FinalLRN = Convert.ToString(addLRN);

        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "select LRN FROM Student_LRN where LRN = '" + FinalLRN + "'";

            OleDbDataReader reader = command.ExecuteReader();

            int countLRN = 0;
            while (reader.Read())
            {
                countLRN++;

            }
            if (countLRN == 0)
            {
                label_LRN.Text = FinalLRN;
            }
            else if (countLRN == 1)
            {
                long randomNewLRN = rnd.Next(1000000000);
                long newLRN = 100000000000 + randomNewLRN;
                string newFinalLRN = Convert.ToString(newLRN);
                label_LRN.Text = newFinalLRN;
                /*
                 * what if this another random generated number already existing again? what can i do with this?
                 */
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
        finally
        {
            connection.Close();
        }

将您的 "check if it is already existing" 逻辑提取到一个您可以在需要时调用的方法中。例如,它可以将 ID 作为参数和 return 布尔值。

如果您想使用该唯一编号来注册用户,我不会使用数值,而是 NewGuid :

// using System;

Guid LRN = Guid.NewGuid();
Console.WriteLine(LRN);

这输出类似:

df7df6cf-59b5-4bfb-87de-0d1e00c003a8

如果该数字存在,您可能需要执行 1 个以上的查询,无论如何具有如此高的值,它会通过类似此代码的一些步骤(1 或 2)解决它

Random rnd = new Random();
long firstLRN;
long addLRN;
string FinalLRN;

try
{
    // Set connection
    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;

    // Generate the first random number
    firstLRN = rnd.Next(1000000000);
    addLRN = 100000000000 + firstLRN;
    FinalLRN = Convert.ToString(addLRN);

    // Query and if exists query with number++
    do {
        command.CommandText = "select LRN FROM Student_LRN where LRN = '" + FinalLRN + "'";

        // Execute the query and check if the number exists
        OleDbDataReader reader = command.ExecuteReader();

        // If number exists add 1 to the number
        if (reader.Read()){
            addLRN++;
            FinalLRN = Convert.ToString(addLRN);
        }
        else {
            break;
        }
    }

}
catch (Exception ex)
{
    MessageBox.Show("Error" + ex);
}
finally
{
    connection.Close();
}