登录程序While循环失效,始终返回‘用户名或密码错误’求助
Hey there! Let's break down why your login code keeps showing that "Incorrect UserName and Password" message, even when you enter valid credentials. Here are the key issues and fixes to get things working:
1. Critical SQL Syntax Error + Security Risk
Your query has a tiny but fatal syntax mistake: there’s no space between the closing quote of the username and the AND keyword. This makes your database interpret something like 'johndoe'and as a single invalid value, so it never finds a matching record.
On top of that, directly plugging user input into SQL queries is a huge security hole (it leaves you open to SQL injection attacks). You should always use parameterized queries instead—they fix syntax issues and keep your app safe.
2. Flawed Condition Logic
Your current condition structure has a bug: the else block is paired with the if (count > 1) check, not the initial count == 1 check. That means even when count == 1 (a valid login), after hiding the current form and showing the new one, it will still run the else block and pop up the error message. Oops!
3. Potential Database Setup Issues
Double-check these details too:
- Your connection string correctly points to the Access database in the
bin/Debugfolder. If the database file isn’t copied to the output directory when you build, your program will be looking at an empty or non-existent database. - The field names in your
logintable exactly matchUserNameandPassword(Access is case-insensitive, but it’s worth confirming). - The credentials you’re entering match exactly what’s in the database—no extra spaces, accidental capitalization differences, etc.
Fixed Code
Here’s the corrected version of your login button handler, addressing all the above problems:
private void loginButton_Click(object sender, EventArgs e) { try { // Parameterized query to avoid syntax errors and SQL injection string loginQuery = "SELECT * FROM login WHERE UserName = ? AND Password = ?"; // Use using statements to auto-dispose resources using (OleDbCommand command = new OleDbCommand(loginQuery, connection)) { // Add parameters for user input command.Parameters.AddWithValue("@UserName", userTextBox.Text); command.Parameters.AddWithValue("@Password", passwordTextBOx.Text); connection.Open(); using (OleDbDataReader reader = command.ExecuteReader()) { int matchCount = 0; while (reader.Read()) { matchCount++; } // Fix condition flow with if-else if-else if (matchCount == 1) { this.Hide(); Form newForm = new Form(); newForm.Show(); } else if (matchCount > 1) { MessageBox.Show("Duplicate UserName and Password found"); } else { MessageBox.Show("Incorrect UserName and Password"); } } } } catch (Exception ex) { MessageBox.Show($"Error occurred: {ex.Message}"); } finally { // Make sure connection is closed even if an error happens if (connection.State == ConnectionState.Open) { connection.Close(); } } }
Key Improvements:
- Parameterized Query: Eliminates syntax bugs and protects against SQL injection.
- Proper Condition Flow: Uses
if-else if-elseso only one outcome runs per login attempt. usingStatements: Automatically cleans up command/reader objects to prevent resource leaks.finallyBlock: Guarantees the database connection gets closed, even if an error pops up.
内容的提问来源于stack exchange,提问作者S.R

