我想在Visual Studio 2010上创建一个注册和登录表单(使用Visual C#) 我创建了基于服务的数据库和一个表。我可以将数据插入表格(在注册表格中),但我无法弄清楚如何登录用户。
我有一个非常简单的登录表单(只是用户名和密码的字段)和一个“登录”按钮。我真的不知道如何检查密码和用户名(我的数据库中存在的)是否匹配。以下是我到目前为止的情况:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" & textBox2.Text != "")
{
cn.Open(); // cn is the Sqlconnection
cmd.Parameters.AddWithValue("@Username", textBox1.Text); // cmd is SqlCommand
cmd.Parameters.AddWithValue("@Password", textBox2.Text);
if (cmd.CommandText == "SELECT * FROM Table1 WHERE username = @Username AND password = @Password")
{
MessageBox.Show("Loggen In!");
this.Close();
}
cn.Close();
}
}
答案 0 :(得分:4)
您需要执行查询以了解数据库中是否存在信息
if (textBox1.Text != "" & textBox2.Text != "")
{
string queryText = @"SELECT Count(*) FROM Table1
WHERE username = @Username AND password = @Password";
using(SqlConnection cn = new SqlConnection("your_connection_string"))
using(SqlCommand cmd = new SqlCommand(queryText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("@Username", textBox1.Text);
cmd.Parameters.AddWithValue("@Password", textBox2.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
MessageBox.Show("Loggen In!");
else
MessageBox.Show("User Not Found!");
}
}
我还在代码中更改了一些内容。
我还建议您更改密码的存储方式 在密码字段中存储散列而不是明确密码。然后将相同的哈希值传递给数据库,并将其与数据库字段的内容进行比较 通过这种方式,密码只为您的用户所知,而不是由您或任何查看数据库表的路人知道
答案 1 :(得分:0)
SqlConnection con = new SqlConnection("connection_string");
SqlCommand cmd = new SqlCommand("select Count(*) from [dbo].[Table] where uname=@uname and password=@password");
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@uname", uname.Text);
cmd.Parameters.AddWithValue("@password", password.Text);
int Result=(int)cmd.ExecuteScalar();
if (Result > 0)
{
Response.Redirect("welcome.aspx");
}
else
{
Response.Redirect("register.aspx");
}