检查数据库中的用户名和密码

本文关键字:密码 用户 数据库 检查 | 更新日期: 2023-09-27 18:33:08

我正在使用 asp.net 创建一个网站。到目前为止,我已经完成了一个注册页面,该页面将详细信息保存到数据库表中。

我将如何检查该表中是否有用户名和密码,然后允许他们进入下一页?

这是我的注册代码;

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["userinfo.ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT INTO [user] (UserName, FirstName, LastName, Email, Password, Country) VALUES (@uname, @fname, @lname, @email, @password, @country)";
SqlCommand comm = new SqlCommand(insertQuery, conn);
comm.Parameters.AddWithValue("@uname", usernametextbox.Text);
comm.Parameters.AddWithValue("@fname", fnametextbox.Text);
comm.Parameters.AddWithValue("@lname", lnametextbox.Text);
comm.Parameters.AddWithValue("@email", emailtextbox.Text);
comm.Parameters.AddWithValue("@country", DropDownListcountry.Text);
comm.Parameters.AddWithValue("@password", passwordtextbox.Text);
comm.ExecuteNonQuery();
conn.Close();

我猜我需要创建一个带有 if 语句的 SELECT 查询?

检查数据库中的用户名和密码

Kris,

你在这个问题上得到了反对票,因为你问了一些你可以使用谷歌很容易自己弄清楚的事情。

话虽如此,是的,您是正确的,您需要使用 SELECT 语句。 我不会给你确切的.NET或SQL语法,因为这会剥夺你的学习经验。 但是,弄清楚如何执行 SELECT COUNT 查询。 您基本上希望计算提供的用户名和密码已存在的行数。 不使用 ExecuteNonQuery,而是使用 ExecuteScalar,它返回单个值。

然后在 .NET 代码中,查看返回的计数值。 如果为 0,请继续。如果大于 0,请执行其他操作。

话虽如此,.NET 有一些内置工具可以为您完成所有这些工作。找到它们并使用它们!

将来,在来这里寻求帮助之前,请尝试花更多的时间自己做一些研究。

祝你好运!

如果您在登录页面中使用文本框作为用户名和密码。

      string connectionstring = WebConfigurationManager.ConnectionStrings["userinfo.ConnectionString"].ConnectionString;
                string sqlstring;
                sqlstring = "Select UserName,Password from user  where UserName='" + 
Texboxusername.Text + "' and Password ='" + Textboxpassword.Text + "'";
                SqlConnection con = new SqlConnection(connectionstring);
                SqlCommand command = new SqlCommand(sqlstring, con);
                System.Data.SqlClient.SqlDataReader reader;
                // open a connection with sqldatabase
                con.Open();
                reader = command.ExecuteReader();
                if (reader.Read())//Reader.read() true if found in database
                {
        Response.Redirect("userHome.aspx");
        }
        con.close();

第二种解决方案是使用表单身份验证。将"从工具箱登录"添加到登录设计页面。单击它两次。在相同的代码旁边,但 Texboxusername.Text 和 Textboxpassword.Text 使用 Login.Username 和 Login.Password。

 if (reader.Read())
{ e.Authenticated = true;}
else{e.Authenticated=false;}

最后在 Web.config 中将其添加到某个地方<system.web> .. </system.web>;

   <forms loginUrl="login.aspx" defaultUrl="userHome.aspx" timeout="60"/>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

经过身份验证后,用户将自动重定向到 defaultUrl,并且由于 .如果你有一个关于UnobtrusiveValidationMode的错误。将其添加到<configuration>... </configuration>;

<add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>