如果用户有效,如何传递标签,我使用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";
答案 0 :(得分:1)
行
userid = cmd.ExecuteNonQuery();
会给你单个对象。
您必须使用cmd.ExcuteReader()
代替。
或者您可以使用查询计算用户数
string selectstr = "select
count(UserName)
from
Registration
where
UserName ='" + UserName + "'
And Password = '" + Password + "'";
并查看计数。
答案 1 :(得分:-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;
}
}