简体   繁体   中英

How to search database in Visual Studio? (C#)

I am working on a side project(student, not homework, just holiday curiosity), which would be my simple personal password manager/vault. It will be a windows app. I want it to support more than just one user. Now that i have my login screen and other functionalities, i struggle to find a simple and effective way to check if login and password of the user are correct. I store the information in a simple SQL table called Users(picture below). Now, i want to get the bool result, whether are these two strings (username,password) in database. i will include some code and screenshots below. Any help appreciated!

PS: I am pretty familiar with mySQL(Oracle), i just can´t fin a good way to do this without being ridiculous. :)

namespace KeyLocker.Database {
[Serializable]
public class UserDatabase {
    public void AddUser(string username,string password,string question,string answer) {
        using(var db = new KeyLockerContext()) {
            db.Add(new User { Username = username,Password = password,SecurityQuestion = question,SecurityAnswer = answer });
            db.SaveChanges();
        }
    }

    public bool CheckUser(string username,string password) {
        using(var db = new KeyLockerContext()) {
            /*here i need to find out if username is present in database
              and if it is, i need to find out if the password is correct*/
        }
    }
}

}

Table Users ScreenShot

Table SQL detail

At first glance, it seems like the easiest code to execute your idea would be:

public bool CheckUser(string username,string password) {
    using(var db = new KeyLockerContext()) {

        // Check if that combination already exists in DB.
        var result = db.Users.Where(x => x.Username == username && x.Password == password).SingleOrDefault();

        // See if result has a value, SingleOrDefault() returns null if no match
        return (result == null);
    }
}

EDIT/Disclaimer: Since there seems to be some confusion, this is an idea for how to quickly check if an object w/ certain values already exists in the DB - not a complete authentication library. You should never store cleartext passwords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM