在数据库中重复输入 [英] Double entry in database

查看:68
本文介绍了在数据库中重复输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,
看看我写的代码

Hello friends,
Just look at code i have written

UserBLL
public class UserBLL
{
	public UserBLL()
	{
		
	}
    public Int32 saveUserDetails(clsUser objUser)
    {
        UserDAO objADO = new UserDAO();
        return objADO.saveUserDetails(objUser);
    }
}





UserDAO
    public int saveUserDetails(clsUser objUser)
    {
        SqlCommand objCmd = new SqlCommand("usp_InsertNewUser");
        object result;
        try
        {
            objCmd.Connection = objCon;
            objCmd.CommandType = CommandType.StoredProcedure;
            objCmd.Parameters.AddWithValue("@username", objUser.username.ToString());
            objCmd.Parameters.AddWithValue("@pwd", objUser.pwd.ToString());
            objCmd.Parameters.AddWithValue("@fname", objUser.firstname.ToString());
            objCmd.Parameters.AddWithValue("@lname", objUser.lastname.ToString());
            objCmd.Parameters.AddWithValue("@contact", objUser.contact.ToString());
            
            if (objCon.State == ConnectionState.Closed)
            {
                objCon.Open();
            }
            result = objCmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            return -1;
        }
        finally
        {
            objCmd.Dispose();
        }
        return Convert.ToInt32(result);
    }



事实是,一切正常,但记录被添加了两次.任何想法,我要去哪里错了. .??

这条线有问题吗?



Thing is that, every thing going fine but records are added twice. Any idea where I''m going wrong. .??

Is this line be problem

return objADO.saveUserDetails(objUser);

推荐答案

在哪里呼叫objUserBLL.saveUserDetails(objUser),如果它在Page_Load中,那么您需要检查IsPostBack以确定该呼叫是否是第一个页面加载或回发.

除了检查objUserBLL.saveUserDetails(objUser)的调用位置之外,您还可以做其他几件事,因为用户名应该是唯一的;
1)在存储过程usp_InsertNewUser中,检查用户名,并仅在数据库中不存在用户名的情况下插入信息.
2)在数据库中的用户名字段上放置一个唯一的约束.
Where are you calling objUserBLL.saveUserDetails(objUser) if it is in Page_Load then you need to check IsPostBack to determine if the call is the first page load or a postback.

Other than checking where objUserBLL.saveUserDetails(objUser) is being called there are a couple of other things you can do as usernames should be unique;
1) In your stored procedure usp_InsertNewUser do a check on the username and only insert the information if the username does not already exist in the database.
2) Place a unique constraint on the username field within the database.


这篇关于在数据库中重复输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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