检查数据库3中的相同用户名

时间:2014-06-26 05:29:05

标签: c# winforms

我只想检查该用户是否存在,如果没有,则保存在数据库中,否则显示错误消息用户已存在 在我使用此命令之前完美运行

SqlCommand cmd = new SqlCommand("Select count(*) from cntc_employee where emp_alias= @alias", con);
cmd.Parameters.AddWithValue("@alias", this.alias.Text);
con.Open();

if(Convert.ToInt32(cmd.ExecuteScalar()) > 0)
{            
    errorProvider1.SetError(alias,"Alias Already exist");
    return true;
}
else
{
    return false;
}

但在3层我不知道如何在if()部分的bll类中使用executioncalar 在我的班级

private bool UserNameCheck(string alias) 
{
    if (??)
        throw new Exception("Alias Already exist");
    else
        return true;
}

在我的dal课程中

public void UserNameCheck(string alias)
{
    string query6;
    try
    {
        OpenCnn();

        query6 = "Select count(*) from cntc_employee where emp_alias= '" + alias + "' ";
        cmd = new SqlCommand(query6, con);
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        CloseCnn();
    }
}

4 个答案:

答案 0 :(得分:0)

让我们从数据访问层开始。虽然你的逻辑似乎是正确的,但我认为你返回物体的方式。在我看来,你最好返回一个指示用户是否存在的布尔值。此外,使用参数化查询,因为您不希望SQLInjection。见代码:

// Note: I changed the name to a more meaningfull use
public static bool UserExists(string alias)
{
    bool userExists = false;
    try
    {
        // Note: where do you initialise cmd?
        cmd.Parameters.AddWithValue("alias", alias);
        cmd.CommandText = "Select count(*) from cntc_employee where emp_alias=@alias";
        cmd.Connection = con;
        OpenCnn();
        int amountOfUsersWithAlias = (int)cmd.ExecuteScalar();
        if(amountOfUsersWithAlias > 0)
              userExists = true;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        CloseCnn();
    }
    return userExists;
}

所以现在你有一个booleanvalue来指示用户是否存在。如果returnvalue为true,则表示存在用户。如果为false,则表示用户不存在。

现在,在您的Businesslayer中,您调用上述方法:

public bool UserNameCheck(string alias)
{
    if (UserClass.UserExists(alias))        
        return true
    else            
        return false;
}

您可以使用静态方法调用正确的别名。同样,返回true或false,具体取决于用户是否存在。然后,在表示层中使用此方法,如果返回true,则向用户显示错误。

它可能不是完美的3层架构,但它可以完成这项工作。

答案 1 :(得分:0)

public String UserNameCheck(String alias) 
{
String returnValue = String.Empty;
SqlCommand cmd = null;
SqlDataAdapter adapter = null;
DataTable dt = null;
try
{
OpenCnn();
cmd =new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select count(*) from cntc_employee where emp_alias=@alias"; 
cmd,Parameter.Clear();
cmd.Parameter.AddWithValue("@alias", alias);
dt = new DataTable();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
if(dt.Rows.Count > 0)
returnValue = "userNameIsExist";
else
returnValue = "userIsNotFound";
} 
catch (Exception ex) 
{
throw ex; 
} 
finally 
{ 
if(dt != null) { dt.Dispose(); dt = null; }
if(adapter != null) { adapter.Dispose(); adapter null; }
if(cmd != null) { cmd.Parameter.Clear(); cmd.Dispose(); cmd = null; }
CloseCnn();
}
return returnValue;
}

答案 2 :(得分:0)

这正是你应该使用stored procedure的东西。 请考虑以下情形:

2个用户同时提交相同的用户名。您的代码进入数据库,检查用户名是否存在,两者都返回false,然后为两个用户插入相同的用户名。

您可以使用存储过程执行这两个操作,而不是检查用户名是否存在于一个查询中并将其插入另一个查询中,从而确保您不会尝试两次添加相同的用户名。 我还建议在该数据库表的用户名上为用户名创建unique constraint(可能是索引,甚至可能是主键,具体取决于您的需要)。

尝试以下sql:

CREATE PROCEDURE stp_InsertUser (
    @RequestedUserName nvarchar(10),
    @OutUserAlrearyExists bit OUTPUT
)
AS

SET @OutUserAlrearyExists = 1
IF NOT EXISTS(
    SELECT 1
    FROM TblUsers
    WHERE Users_UserName = @RequestedUserName
) BEGIN
    INSERT INTO TblUsers(Users_UserName) VALUES (@RequestedUserName)
    SET @OutUserAlrearyExists = 0
END

GO

然后在您的代码中,您所要做的就是执行此存储过程。 这也带来了另一个好处 - 而不是只去一次数据库2次。

答案 3 :(得分:-1)

试试这个(私人):

        private int UserExistCheck(string alias)
    {
        string query6;
        try
        {
            OpenCnn();

            query6 = "Select count(*) from cntc_employee where emp_alias= '" + alias + "' ";
            cmd = new SqlCommand(query6, con);
            return cmd.ExecuteScalar(); //-- or ExecuteNonQuery()
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            CloseCnn();
        }
    }

和这(公开):

        public bool UserNameCheck(string alias)
    {
        if (UserExistCheck(alias) > 0)
        {
            throw new Exception("Alias Already exist");

        }
        else
        {
            return true;
        }
    }
希望能帮助你

编辑:

PersonDAL:

    public class PersonDAL
{
    string connStr = ConfigurationManager.ConnectionStrings["TutTestConn"].ToString();

    public PersonDAL()
    {

    }

    public int Insert(string firstName, string lastName, int age)
    {
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();
        SqlCommand dCmd = new SqlCommand("InsertData", conn);
        dCmd.CommandType = CommandType.StoredProcedure;
        try
        {
            dCmd.Parameters.AddWithValue("@firstName", firstName);
            dCmd.Parameters.AddWithValue("@lastName", lastName);
            dCmd.Parameters.AddWithValue("@age", age);
            return dCmd.ExecuteNonQuery();//-- if combination of user name and
        }                                 // password are not unique throw exception
        catch
        {
            throw;
        }
        finally
        {
            dCmd.Dispose();
            conn.Close();
            conn.Dispose();
        }
    }}

和PersonBAL:

public class PersonBAL
{
    public PersonBAL()
    {

    }

    public int Insert(string firstName, string lastName, int age)
    {
        PersonDAL pDAL = new PersonDAL();
        try
        {
            return pDAL.Insert(firstName, lastName, age);
        }
        catch
        {
            throw;
        }
        finally
        {
            pDAL = null;
        }
    }
}