我正在从我的本地MySQL数据库在C#visual studio中创建一个登录表单。但是,每当我输入信息时,它告诉我用户名和/或密码不正确,我知道这是错误的。 这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
public partial class Form1 : Form
{
private MySqlConnection connection = new MySqlConnection();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_Login_Click(object sender, EventArgs e)
{
try
{
String MyConnection = "datasource = localhost; port = 3306; username = root; password = Mypass;";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand SelectCommand = new MySqlCommand("SELECT * FROM dark_heresy.users WHERE users_='"+ this.TextUserName.Text + "' and password_='"+ this.TextPassword.Text + "';", MyConn);
MySqlDataReader MyReader;
MyConn.Open();
MyReader = SelectCommand.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
count = count++;
}
if (count == 1)
{
MessageBox.Show("Connection Successful");
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
MessageBox.Show("Incorrect Username and/or Password");
MyConn.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error: \r\n" + exp);
}
}
}
}
在MySQL工作台中它起作用,它在显示时向我显示“用户”及其“密码”:
SELECT * FROM dark_heresy.users WHERE users_='admin' and password_='adminpass';
连接正常,已经过测试,但总是得到“用户名和/或密码不正确”的结果。
答案 0 :(得分:3)
除了您的代码中存在更多问题之外,您的问题还是
count = count++;
后缀增量会增加count
,但会返回其先前的值。
string connectionString = "datasource = localhost; port = 3306; username = root; password = Mypass;";
using(MySqlConnection myConn = new MySqlConnection(connectionString))
using(MySqlCommand selectCommand = new MySqlCommand())
{
selectCommand.CommandText = "SELECT COUNT(1) FROM dark_heresy.users WHERE users_=@User and password_=@Password";
selectCommand.Connection = myConn;
selectCommand.Parameters.Add(new MySqlParameter("User", MySqlDbType.VarChar).Value = TextUserName.Text);
selectCommand.Parameters.Add(new MySqlParameter("Password", MySqlDbType.VarChar).Value = TextPassword.Text);
myConn.Open();
var ret = selectCommand.ExecuteScalar();
var count = Convert.ToInt32(ret);
if (count == 1)
{
MessageBox.Show("Connection Successful");
}
else if (count > 1)
{
MessageBox.Show("Duplication of Username and Password... Access Denied");
}
else
{
MessageBox.Show("Incorrect Username and/or Password");
}
}