首页 > 解决方案 > 如何检查我的号码是否是数据表中有价值的 id?

问题描述

我想检查我的随机生成的数字是否与我的数据表中的 [id] 匹配,这是必要的,以便我可以通过 id 从表中获取随机值。我想出什么:

            Random rnd = new Random();
            int card = rnd.Next(1,21);
            label8.Text = Convert.ToString(card);

            try
            {
                while (await sqlReader.ReadAsync())
                {
                    string find = "item_manuf_id = 'some value'";
                    DataRow[] foundRows = table.Select(find);
                }
            }

感谢 rufus L,现在我想出了这样的代码:

string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\project vstudio\ShefPowarSln\ShefPowar\Database.mdf;Integrated Security=True";

            Random rnd = new Random();
            int card = rnd.Next(1, 21);

            bool isValidId = false;
            string sqlQuery = "SELECT [Id] from [Recipes] where [Id] = @id";

            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(sqlQuery, connection))
            {
                connection.Open();
                var idParam = new SqlParameter("id", SqlDbType.Int);
                idParam.Value = card;
                command.Parameters.Add(idParam);
                var result = command.ExecuteReader();
                if (result.HasRows) isValidId = true;
                if (isValidId == true) label9.Text = "Yass";
            }

标签: c#winformsdatatablesmdf

解决方案


听起来您只需要在数据库中查询item_manuf_id字段与card值匹配的某个表中的任何记录:

bool isValidId = false;
string query = "SELECT [item_manuf_id] from [tableName] where [item_manuf_id] = @id";

using (SqlConnection con = new SqlConnection(/* connection info */))
using (SqlCommand cmd = new SqlCommand(query, con))
{
    var idParam = new SqlParameter("@id", SqlDbType.Int);
    idParam.Value = card;
    cmd.Parameters.Add(idParam);
    var result = cmd.ExecuteReader();
    if (result.HasRows) isValidId = true;
}

// isValidId  will be 'true' if any records for that id were found

推荐阅读