我正在尝试使用 sql 连接创建登录表单。当我按下登录按钮(按钮2)时,无论文本框中是否有文本,表单都会冻结。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Test2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\tfgge\\Documents\\BazaDate.mdf;Integrated Security=True;Connect Timeout=30;Encrypt=True");
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Autentificare where EmailUtiliz = @email and ParolaUtiliz = @parola", con);
cmd.Parameters.AddWithValue("email", textBox1.Text);
cmd.Parameters.AddWithValue("parola", textBox2.Text);
var read = cmd.ExecuteReader();
if(read.Read())
{
MessageBox.Show("Autentificare reusita");
}
else
{
MessageBox.Show("Autentificare esuata");
}
}
}
}
我尝试使用私有类进行连接,但遇到了一些异常,这是我最终得到的变体。
执行命令后尝试关闭连接。
private void button2_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Autentificare where EmailUtiliz = @email and ParolaUtiliz = @parola", con);
cmd.Parameters.AddWithValue("@email", textBox1.Text);
cmd.Parameters.AddWithValue("@parola", textBox2.Text);
var read = cmd.ExecuteReader();
if(read.Read())
{
MessageBox.Show("Autentificare reusita");
}
else
{
MessageBox.Show("Autentificare esuata");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
con.Close(); // Close the connection after executing the command
}
}
我发现了几个问题。最直接的是使用双反斜杠字符和
@
逐字字符串前缀,但这里的其他更正也很重要:
public partial class Form1 : Form
{
string cnString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\tfgge\Documents\BazaDate.mdf;Integrated Security=True;Connect Timeout=30;Encrypt=True";
private void button2_Click(object sender, EventArgs e)
{
using var con = new SqlConnection(cnString);
using var cmd = new SqlCommand("SELECT ParolaUtiliz FROM Autentificare WHERE EmailUtiliz = @email", con);
cmd.Parameters.Add("@email", SqlDbType.NVarchar, 60).Value = textBox1.Text;
con.Open();
var storedHash = (string)cmd.ExecuteScalar();
//assuming the BCrypt.Net library on NuGet
if (storedHash is object && BCrypt.Verify(textBox2.Text, storedHash))
{
MessageBox.Show("Autentificare reusita");
}
else
{
MessageBox.Show("Autentificare esuata");
}
}
}
另一件事:您确实应该为控件和事件方法提供更好的名称。以后你会感谢自己的。