我使用C#visual studio从本地MySQL数据库创建登录表单。然而,每次我输入信息时,都会告诉我用户名和/或密码不正确,我知道这是错误的。 这里是代码:C#MySQL无法识别输入
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';
的连接工作正常,它有已经过测试,但总是得到结果“不正确的用户名和/或密码”。
要解决的第一件事就是停止像这样创建SQL - 使用参数化SQL。有关原因,请参阅http://www.bobby-tables.com。接下来,停止在数据库中以明文形式输入密码。理想情况下,使用其他人编写的认证系统......实际上没有理由把自己放在一起,而且会让用户的安全处于危险之中。 – 2014-11-21 17:13:47
噢,对于需要计算记录数的类似情况,请在查询中使用COUNT并使用ExecuteScalar来执行它。 – 2014-11-21 17:14:47
并且你不需要计数,只要检查一行的存在,使用'EXISTS'。 – HABO 2014-11-21 17:19:13