简体   繁体   English

C# 检查数据是否已经存在

[英]C# Check if the data already exists

I have a product record table in the database, it will save the following: ID, product code, product name, size, and price.我在数据库中有一个产品记录表,它将保存以下内容:ID、产品代码、产品名称、尺寸和价格。 A product can have the same size and price right?一个产品可以有相同的尺寸和价格吗? In my code, I am trying to check if the data already exists, if it already exists it won't save but if not it will save.在我的代码中,我试图检查数据是否已经存在,如果已经存在则不会保存,但如果不存在则会保存。 I already tried saving a different name and size of the product but with the same price but it would say that it already exists.我已经尝试保存产品的不同名称和尺寸,但价格相同,但它会说它已经存在。 I am new to c# and this is in WinForms, I searched it up here but I don't understand it and it is on other language.我是 c# 的新手,这是在 WinForms 中,我在这里搜索过,但我不明白,它是其他语言的。 I only know java so far.到目前为止我只知道java。 I guess this error is a logical error, but I don't know what to do.我猜这个错误是一个逻辑错误,但我不知道该怎么办。

This is what I tried so far,这是我到目前为止尝试过的,

cmd = new SqlCommand("select Product_Code from ProductRecord where Product_Code = @Product_Code", con);
cmd.Parameters.AddWithValue("@Product_Code", tbpcCode.Text);
DataTable dt = new DataTable();
adapt.Fill(dt);
if ( dt.Rows.Count >= 1 )
{
  MessageBox.Show("Record Already Existing");
}
else
{
  // Do save
}

You don't have to open connection to the database each time you create a product.您不必在每次创建产品时都打开与数据库的连接。 In fact you can rely on the Product_Code field in your database and change it to a unique key constraint see Microsoft docs here so its going to block the insertion of duplicate products.实际上,您可以依赖数据库中的 Product_Code 字段并将其更改为唯一键约束,请参阅此处的 Microsoft 文档,以便阻止重复产品的插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM