【发布时间】:2021-09-24 09:44:44
【问题描述】:
我是初学者,刚接触 C#,我不知道如何修复这个错误,请帮助 SQL 服务正在运行,VS2019 更新到最新版本,我是 Windows 11。 它只说 Exception throw: 'System.Data.SqlClient.SqlException' in System.Data.dll 代码:
string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LoginDB.mdf;Integrated Security=True;";
private void Loginbutton_Click(object sender, EventArgs e)
{
if (LoginTextBox.Text == "" || PassTextBox.Text == "") // Nếu 1 trong 2 ô trống thì
{
MessageBox.Show("Missing login name or password");
return;
}
try
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Select * from LoginDB where UserName=@username and Password=@password", con);
cmd.Parameters.AddWithValue("@username", LoginTextBox.Text);
cmd.Parameters.AddWithValue("@password", PassTextBox.Text);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
//If count =1 thì hiện f2(Menu)
if (count == 1)
{
MessageBox.Show("Login Successfully!");
this.Visible = false;
Menu f2 = new Menu();
f2.Show();
}
else
{
MessageBox.Show("Login Name or password is wrong");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
【问题讨论】:
-
异常说明了什么以及它在哪一行抛出?
-
Sql 服务?还是 SQL Server?
-
根据我的经验:dataadapter 会自动打开和关闭连接。所以避免在一个连接中使用 sqlcommand 和 dataadapter。
-
它只说异常抛出:System.Data.dll中的'System.Data.SqlClient.SqlException'
-
这是 Sql 服务
标签: c# winforms connection-string sqlexception system.data.sqlclient