asp.net 连接数据库

本文介绍了一个使用ASP.NET和SQL Server进行用户登录验证的示例代码。通过获取前端传入的用户名和密码,利用SqlConnection连接本地数据库,并执行SqlCommand查询用户信息。如果查询到匹配的记录,则返回登录成功的消息;否则,返回用户名或密码错误的提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = “text/html; charset=utf-8”;
//前台传入参数
string name = context.Request.Params[“name”];
string pass = context.Request.Params[“pass”];
SqlConnection conn = new SqlConnection();
//数据库连接字符串
conn.ConnectionString = “Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\vs_project\testdb.mdf;Integrated Security=True;Connect Timeout=30”;
string commandText = “select top 1 * from userinfo where name=@name and pass=@pass”;
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add(“name”, SqlDbType.NChar, 10).Value = name;
cmd.Parameters.Add(“pass”, SqlDbType.NChar, 10).Value = pass;
string str = “”;
try
{
conn.Open();
SqlDataReader thisSqlDataReader = cmd.ExecuteReader();
//读取查询数据
while (thisSqlDataReader.Read())
{
str += thisSqlDataReader[“id”] + “|” + thisSqlDataReader[“name”] + “|” + thisSqlDataReader[“pass”] + “|” + thisSqlDataReader[“roletype”];
}
conn.Close();
}
catch (Exception e)
{
context.Response.Write(e);
return;
}
if (!str.Equals(“”))
{
context.Response.Write(“恭喜您,登陆成功!” + str);
return;
}
context.Response.Write(“用户名或密码错误!”);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值