1

如果用户有效与否如何传递标签,我正在使用带有应用程序设置的 3 层架构。所以你能指导我如何传递标签,无论用户是否有效

     public static int login(string UserName, string Password)
            {

                SqlConnection con = new SqlConnection();
                con.ConnectionString = GetConnectionString();
                con.Open();
                int userid = 0;
                string selectstr = "select UserName,Password from Registration  where UserName =' " + UserName + " ' And  Password = ' " + Password + " ' ";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = selectstr;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = con;
                userid = cmd.ExecuteNonQuery();
                cmd = null; 
                con.Close();

                return userid;

           if(......... ?)
{
labet.Text = " valid";
} else
{
label.Text = " not valid";
4

2 回答 2

1

线

userid = cmd.ExecuteNonQuery();

会给你一个对象。

你将不得不使用cmd.ExcuteReader()


或者您可以计算使用查询的用户数量

string selectstr = "select 
                         count(UserName)                             
                     from 
                         Registration  
                      where 
                         UserName ='" + UserName + "' 
                         And  Password = '" + Password + "'";

看看计数。

于 2013-03-07T09:57:41.113 回答
-1

您的代码可以优化很多。首先我必须告诉你,你最好使用参数,try-catch 和 ExecuteScalar。ExecuteScalar 将返回一个单格整数。有了它,您可以验证用户身份验证。

编辑:

    public static void login(string UserName, string password)
    {
        SqlConnection con = new SqlConnection(GetConnectionString());
        try
        {
            con.Open();

            string selectstr = "select count(id) from Registration  where UserName=@username And  Password=@password";

            SqlCommand cmd = new SqlCommand(selectstr, con);
            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@password", password);

            int result = cmd.ExecuteScalar();
            cmd.Dispose();
            con.Close();

            if (result == 1)
            {
                label.Text = "valid";
                //valid
            }
            else
            {
                //not
            }
        }
        catch
        {
            throw;
        }
    }
于 2013-03-07T10:02:14.783 回答