如何避免使用C#将相同的数据插入数据库 [英] how to avoid to insert same data into database using C#

查看:418
本文介绍了如何避免使用C#将相同的数据插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个数据库名称为email_book;并且在该数据库中有一个名为contact_book的表.... name和mail_id是我在该表中创建的两列.......现在我想将数据添加到我的表中在C#中使用表单但是在计数器部分我只是想避免将重复的数据插入到表中.......当用户添加已经存在于表中的相同mail_id时,它必须给出消息this mail_address已经存在于数据库中........所以我需要在C#中进行打包#



.....请帮助其紧急

There is one database name as "email_book" and in that database there is one table named as "contact_book"....name and mail_id are the two column which i had been created in that table.......now i want to add data into to my table using form in C# but on the counter part i just want to avoid inserting the repeated data into the table.......when user add same mail_id which is already present in the table then it must gives the message that "this mail_address is already present in database"........so for that i need coading in C#

.....please help its urgent

推荐答案

您可以像这样计算正在插入的数据的值:



You can count the value of data that is being inserted like this:

string constr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
        SqlConnection con = new SqlConnection(constr);
        string sql1 = "SELECT COUNT (client_id) FROM client WHERE client_id = '" + txtid.Text + "' ";
        SqlCommand cmd = new SqlCommand(sql1, con);
        con.Open();
        int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
       if (temp >0)
        {
//show error message
        }


set mail_id列为IDENTITY。这可以防止重复使用密钥。



http: //msdn.microsoft.com/en-us/library/ms186775.aspx [ ^ ]
set mail_id column as IDENTITY. that prevents duplicated key usage.

http://msdn.microsoft.com/en-us/library/ms186775.aspx[^]


这篇关于如何避免使用C#将相同的数据插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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