在数据库中重复输入
问题描述:
你好朋友,
看看我写的代码
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 callingobjUserBLL.saveUserDetails(objUser)
if it is inPage_Load
then you need to checkIsPostBack
to determine if the call is the first page load or a postback.
Other than checking whereobjUserBLL.saveUserDetails(objUser)
is being called there are a couple of other things you can do as usernames should be unique;
1) In your stored procedureusp_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.