我正在使用登录表单,在完成之后,我发现了一个愚蠢的问题!
我输入了一个错误的密码,在我纠正之后我又收到了“错误的密码”!
string username = txt_Username.Text.Trim().ToLower();
string password = txt_Password.Text.Trim();
db.cmd.CommandText = "select count(id) from Users where [username]=@un and [password]=@pw";
db.cmd.Parameters.AddWithValue("@un", username);
db.cmd.Parameters.AddWithValue("@pw", db._md5(password));
我认为这是因为每次cmd想要执行时,@ un和@pw都会得到之前的值,因此我改变了我的代码来测试我的想法:
db.cmd.CommandText = "select count(id) from Users where [username]='"+username+"' and [password]='"+password+"'";
它仍然有相同的结果!
我输入正确的密码后删除了打开新表格的代码,所以现在当你输入正确的密码后输入错误的密码时,会说你的密码是正确的:))
db class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Data.OleDb;
namespace My_Images
{
class Database
{
private string connection_string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database.mdb;Jet OLEDB:Database Password=!@~dbpw~@!;";
public OleDbConnection cn;
public OleDbCommand cmd;
public bool connection_error = false;
public string connection_error_reason;
public string _md5(string txt)
{
byte[] A = ASCIIEncoding.ASCII.GetBytes(txt);
byte[] H = MD5CryptoServiceProvider.Create().ComputeHash(A);
return BitConverter.ToString(H).Replace("-", "").ToLower();
}
public Database()
{
try
{
cn = new OleDbConnection(connection_string);
cn.Open();
connection_error = false;
}
catch(Exception e)
{
connection_error = true;
connection_error_reason = e.Message;
}
if (connection_error == false)
{
cmd = new OleDbCommand();
cmd.Connection = cn;
}
}
}
}
答案 0 :(得分:2)
Ah, now I see it, you only create new SqlCommand cmd
directly after you open the connection. If the first attempt goes wrong you are reusing the same command object. And when you execute the same command twice (just changing the CommandText
does not make it a new command) you use AddWithValue
. But this way you are just appending your values to the existing cmd.Parameters
collection and not replacing the existing values. You have to do a
cmd.Parameters.Clear();
before adding the new values. Otherwise SQL server will always use the first two parameters provided, which are, indeed the ones, you entered the first time and obviously the wrong ones.
答案 1 :(得分:1)
首先检查文本框" txt_Password"
的值您可以将参数添加到cmd,例如..
cmd.Parameters.AddWithValue("@pw", db._md5(password));