最好的办法是在您的数据库上有一个存储过程。这样,您也永远不会在客户端公开密码。
要在您的服务器上创建存储过程,请尝试以下操作:
CREATE PROCEDURE AuthenticateUser
(@username VarChar(25),
@password VarChar(25)) AS
SELECT
COUNT(*)
FROM COMPANY
WHERE Login = @username
AND Password = @password
RETURN @@Rowcount
访问此存储过程的代码如下:
//Open a connection to the database using your connection string
using (SqlConnection con = new SqlConnection("My Configuration string"))
{
//Open the connection
con.Open();
//Create a new command for the stored proc, using the existing connection just opened
using(SqlCommand cmd = new SqlCommand("AuthenticateUser", con))
{
cmd.CommandType = CommandType.StoredProcedure;
//Add the username and password to the command, as paramaters (Prevents a lot of security issues, such as SQL Injection)
cmd.Parameters.Add("@username", SqlDbType.VarChar, 25).Value = UserIdTextBox.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar, 25).Value = "Password";
//A paramater for the return value, which will be a bool (Only 0 or 1 should be returned from the database/stored proc)
SqlParameter ret = new SqlParameter("ret", SqlDbType.Int);
ret.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(ret);
//Execute the query
cmd.ExecuteNonQuery();
if (Convert.ToBoolean(ret.Value) == true)
{
//Login Successful
}
else
{
//Login Failed
}
}
}
SQLParamaters 有助于减少用户可以与您的数据库进行的交互量,因为它会清理输入而不是盲目地接受他们输入的任何内容(这可能导致他们删除您的整个数据库)。
但请记住。您还应该使用哈希和盐密码。如果你想看这个,有一个关于堆栈溢出的问题。不这样做是非常糟糕的做法。