在编辑某些记录时不允许重复 [英] Not allowing duplicates on editing some record

查看:83
本文介绍了在编辑某些记录时不允许重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有电子邮件字段和电子邮件类型的表,我检查了是否存在重复项,但是当我编辑一些记录并仅更改电子邮件类型字段时,它检查了电子邮件是否已经存在,因为我已经更改了只有电子邮件类型,我无法编辑记录,任何人都可以帮助我解决这个问题.我可以使用REPLACE做到这一点吗,recordid是此表的主键.

i have a table with email field and email type, i am done with checking if duplicate exists or not ,but when i edit some record and change only the email type field it checks if the email already exists ,since i have changed only email type i am not able to edit the record,can any one help me with this prob.can i do this with REPLACE,recordid is the primary key for this table.

public bool CheckDuplicate(string Email)
		{
			MySqlCommand cmd=null;
			MySqlDataReader dtr=null;
			bool bRv=false;
			try 
			{
				con.Open();
				string str=string.Format("SELECT * FROM tbl_users_email WHERE tbl_users_emailaddress=''{0}''",Email);
				cmd=new MySqlCommand(str,con);
				dtr=cmd.ExecuteReader();
				while(dtr.Read())
				{
					bRv=true;
				}
				return bRv;
			} 
			catch (Exception ex) 
			{
				throw ex;
			}
                     }

推荐答案

如果您正在编辑记录,为什么要检查它是否存在:您已经知道了.
为什么不只使用Sql UPDATE命令:
If you are editing the record, why are you checking if it exists: you already know it does.
Why not just use the Sql UPDATE command:
cmd = new MySqlCommand("UPDATE tbl_users_email SET email_type=@NEWVALUE WHERE tbl_users_emailaddress=@EMAIL", con);
cmd.Parameters.AddWithValue("@NEWVALUE", newEamilType);
cmd.Parameters.AddWithValue("@EMAIL", Email);


注意:不要通过连接字符串来创建SQL命令,它会使您容易受到意外或故意的SQL注入攻击的攻击,这可能会破坏数据库.改用上面显示的参数化查询.


Note: Do not create SQL commands by concatenating strings, it leaves you wide open to an accidental or deliberate SQL Injection attack, which can destroy your database. Use Parametrized queries as I show above instead.


您可以这样操作.

dtr.Edit
dtr.Email ="YourEmail@EmailServer.Com"
dtr.Update
You can make it this way.

dtr.Edit
dtr.Email ="YourEmail@EmailServer.Com"
dtr.Update


这篇关于在编辑某些记录时不允许重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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