c# - 如何检查我的号码是否是数据表中有价值的 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";
}
解决方案
听起来您只需要在数据库中查询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
推荐阅读
- charts - 如何在 Google Chart API 中使 hAxis 可滚动
- asp.net-core - 运行 dotnet core webapi 项目的问题
- excel - VBA:将格式化的类型(数字)返回到 Excel
- r - tidyverse 和 $ 子集特性?这种行为的意图?
- java - 如何从 inputStream 对象中读取 XML 数据?
- c# - 为什么我的角色在对角线移动时不攻击?
- javascript - 在 Angular 项目中实施测验
- node.js - Node Express - 优化接收缓冲数据并在准备好后发送给用户的例程
- nginx-reverse-proxy - NGNIX 返回 502
- java - 如何拆分数组的字符串元素并将它们添加到另一个?