我正在嘗試創建一個登錄程序,用於檢查用戶輸入的用戶名和密碼是否保存在數據庫中。出於某種原因,該程序的「if(dr.HasRows)」部分不起作用。當我嘗試沒有嘗試抓住,我得到和錯誤「可能錯誤的空聲明」。我做錯了什麼?使用本地SQL數據庫登錄程序
SqlConnection Connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Logins.mdf;Integrated Security=True");
try
{
Connection.Open();
MessageBox.Show("Connection Succesful");
if (Connection != null && Connection.State == ConnectionState.Closed);
SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM Logins WHERE Username='" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", Connection);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
MessageBox.Show("Login Success");
}
else
{
MessageBox.Show("Incorrect login");
}
}
catch (Exception)
{
MessageBox.Show("Connection Unsuccesful");
}
在查詢的末尾添加雙引號;) – Abbas
@Abbas謝謝 – Steve
這就解決了我的問題,謝謝你 – user2840120