[英]Visual Studio Login Page with local SQL server database
I'm creating a visual studio project that uses a local SQL server database as a data source, which is up and running correctly. 我正在创建一个Visual Studio项目,该项目使用本地SQL Server数据库作为数据源,该数据库已正常运行。
I need to create a login form for the project. 我需要为该项目创建一个登录表单。
The form has a username textbox and a password textbox which the user will populate with their details, and then hit the 'login' button, which needs to execute the select sql statement. 该表单具有一个用户名文本框和一个密码文本框,用户将使用其详细信息填充该文本框,然后单击“登录”按钮,这需要执行select sql语句。
Any references on how to do this? 有关如何执行此操作的任何参考?
The code I have tried is below. 我尝试过的代码如下。 It's throwing a NullReferenceException at the line that says "SqlDataReader dr = cmd.ExecuteReader();"
它在显示“ SqlDataReader dr = cmd.ExecuteReader();”的行上引发NullReferenceException。
How do I Solve the nullreferenceexception? 我该如何解决nullreferenceexception?
Thank you! 谢谢!
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");
}
}
Try this 尝试这个
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();
You need to do some research into using ADO.Net, specifically the SQLCommand class. 您需要对使用ADO.Net进行一些研究,尤其是SQLCommand类。
However I would refrain from using inline sql statements like above as this opens you up to SQL injection. 但是,我将避免使用上述内联sql语句,因为这可以使您进行SQL注入。 Rather use paramaterised queries, stored procedures or LINQ to SQL.
而是使用参数化查询,存储过程或LINQ to SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.