我正在编写一个C#窗体,所以当你点击退出时,它会关闭
窗口,当您单击登录时,它会检查登录信息并将您带到
另一种形式,如果它是正确的。当我点击登录时,我收到一个错误,上面写着,
System.Data.dll中发生了类型为“System.Data.SqlClient.SqlException”的未处理异常。它会抛出sda.Fill(dt);
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 System.Data.SqlClient;
namespace LoginForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\carme\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username'" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Check your username and password");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
答案 0 :(得分:1)
也许你应该改变
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username'" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", con);
到
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username ='" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", con);
答案 1 :(得分:0)
您需要打开您的连接,然后您应该使用using语句,因为SqlConnection
和SqlDataAdaptor
实现IDisposable
并且应该关闭。 using语句将为您解决这个问题。
还使用参数来防止SQL注入。
你也忘了用户名后的'='。
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 System.Data.SqlClient;
namespace LoginForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\carme\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;"))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Login where Username = @userName and Password = @passWord, con))
{
sda.SelectCommand.Parameters.AddWithValue("@userName", textBox1.Text);
sda.SelectCommand.Parameters.AddWithValue("@passWord", textBox2.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Main ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Check your username and password");
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
我没有测试过,但看起来它对我来说是对的。