登录 登录
namespace BLL
{
public class UserInfoBLL
{
//登录
public static UserInfo Select(string name, string pwd)
{
return UserInfoDAL.Select(name, pwd);
}
}
}
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
public class SQLherpel
{
//连接字符
private static string strConn = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
//查询
public static DataTable Query(string sql,params SqlParameter[] sqlParameters)
{
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, strConn))
{
if (sqlParameters != null && sqlParameters.Count() > 0)
{
adapter.SelectCommand.Parameters.AddRange(sqlParameters);
}
using (DataTable table = new DataTable())
{
adapter.Fill(table);
return table;
}
}
}
//非查询
public static int NonQuery(string sql,params SqlParameter[] sqlParameters)
{
using (SqlConnection sqlConnection = new SqlConnection(strConn))
{
using (SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection))
{
if (sqlParameters != null && sqlParameters.Count() > 0)
{
sqlCommand.Parameters.AddRange(sqlParameters);
}
sqlConnection.Open();
return sqlCommand.ExecuteNonQuery();
}
}
}
}
}
namespace DAL
{
public class UserInfoDAL
{
public static UserInfo Select(string name,string pwd)
{
//构建查询语句 = 不能like
var sql = $"select * from UserInfo Where name=@name and pwd=@pwd";
SqlParameter[] sqlParameters =
{
new SqlParameter("@name",name),
new SqlParameter("@pwd",pwd)
};
var table = SQLherpel.Query(sql,sqlParameters);
//如果没有数据 null
if(table ==null || table.Rows.Count < 1)
{
return null;
}
//如果有数据,取第一行,转换为对象
var row = table.Rows[0];
UserInfo user = new UserInfo()
{
Id = Convert.ToInt32(row["Id"]),
name = Convert.ToString(row["name"]),
pwd = Convert.ToString(row["pwd"]),
Role = Convert.ToInt32(row["Role"]),
};
return user;
}
}
}
namespace Model
{
public class UserInfo
{
public int Id { get; set; }
public string name { get; set; }
public string pwd { get; set; }
public int Role { get; set; }
}
}
namespace Web
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string name = this.txtName.Text;
string pwd = this.txtPwd.Text;
var user = UserInfoBLL.Select(name, pwd);
if (user==null)
{
Response.Write("<script>alert('账号或者密码不正确')</script>");
}
else if(user.Role==0)
{
//用户
Response.Write("<script>alert('用户登录')</script>");
}
else if (user.Role == 1)
{
//管理员
Response.Write("<script>alert('管理员登录')</script>");
}
}
}
}
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="sql" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True" />
</connectionStrings>
</configuration>