使用C#在WPF中插入数据库时​​如何查找重复记录 [英] How to find duplicate records when insert into database in wpf using C#

查看:176
本文介绍了使用C#在WPF中插入数据库时​​如何查找重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先生,
在我的项目中,我想知道如何在插入时避免重复记录
进入数据库
我的表单之一是状态代码和状态名称文本字段.
我只想插入一次相同的状态代码.
当我尝试再次插入相同的状态代码时,该如何避免呢?


插入的代码如下:
其实我没有写代码来避免重复一次,因为我不完全知道代码


Sir,
In my project I want to know how to avoid the duplicate records when insert
into database
One of my form, there is state code and state name text fields.
I want to insert the same state code only once.
How can I avoid the same state code when one try to insert it again


The code is as follows to insert:
Actually I didn''t write the code to avoid the duplicate once,because I don''t know the code exactly


SqlCommand cmd = new SqlCommand();
                            
String str = "insert into State(Code,Name)values ('" + 
              this.txtstatecode.Text + "','" + this.txtstatename.Text + "')";
cmd.CommandText = str;
cmd.Connection = conn;
cmd.ExecuteNonQuery();                               

DataTable dt = new DataTable();

String str1 = "select code,name from state";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = str1;

SqlDataAdapter adp = new SqlDataAdapter(cmd);
SqlCommandBuilder cb = new SqlCommandBuilder(adp);
                               
adp.Fill(dt);
                                
bs.DataSource = dt;
statedg5.ItemsSource = bs;

adp.Update(dt);
this.datagrid.Items.Refresh();



[修改:在代码中添加了前置标记和修改后的间距]



[Modified: added pre tags and modified spacing in code]

推荐答案

我建​​议您在查询中使用IF NOT EXISTS条件来检查记录是否已存在.

I would suggest you to use IF NOT EXISTS condition in your query to check for already existence of records.

IF NOT EXISTS (SELECT CODE FROM STATE WHERE CODE = ????)
BEGIN
    --INSERT RECORD HERE
END



这样,您将可以单次调用数据库表.



This way you will have a single call to database table.


要检查状态和代码是否存在,请执行带where子句的select语句,指定要查找的状态和代码.

如果select语句不返回任何记录,则该记录不存在,因此将其插入数据库.如果select语句返回一条记录,请不要再次插入它,因为状态和代码已经存在.

例如:

选择代码,从州代码="1234"和名称="Smithville"的名称

另一件事-构建SQL字符串时,您将需要记住处理状态名称中存在的单引号.
To check if a state and code exists, perform a select statement with a where clause specifying the state and code you are looking for.

If the select statement returns no records, it doesn''t exist, so insert it into the database. If the select statement returns a record, do not insert it again as the state and code already exist.

example:

select code, name from state where code = ''1234'' and name = ''Smithville''

Another thing - you will need to remember to handle single quotes that exist in your state names when building your SQL string.


这篇关于使用C#在WPF中插入数据库时​​如何查找重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆