[英]Visual Studio Login Page with local SQL server database
我正在創建一個Visual Studio項目,該項目使用本地SQL Server數據庫作為數據源,該數據庫已正常運行。
我需要為該項目創建一個登錄表單。
該表單具有一個用戶名文本框和一個密碼文本框,用戶將使用其詳細信息填充該文本框,然后單擊“登錄”按鈕,這需要執行select sql語句。
有關如何執行此操作的任何參考?
我嘗試過的代碼如下。 它在顯示“ SqlDataReader dr = cmd.ExecuteReader();”的行上引發NullReferenceException。
我該如何解決nullreferenceexception?
謝謝!
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MARKO-PC\\SQLEXPRESS;Initial Catalog=IS2B_G8_FundMeDB;Integrated Security=True";
con.Open();
String sql = "Select * from APPLICANT where applicant_ID_passport =@user AND password = @password";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add(new SqlParameter("@user", txtUserName.Text));
cmd.Parameters.Add(new SqlParameter("@password", txtPassword.Text));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login Failed");
}
}
catch (SqlException sqle)
{
MessageBox.Show("Sql Exception");
}
}
嘗試這個
string struser = txtUserName.Text;
string strpwd = txtPassword.Text;
String sql = "Select * from APPLICANT where applicant_ID_passport=" + struser + " AND password = " + strpwd +"";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
您需要對使用ADO.Net進行一些研究,尤其是SQLCommand類。
但是,我將避免使用上述內聯sql語句,因為這可以使您進行SQL注入。 而是使用參數化查詢,存儲過程或LINQ to SQL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.