简体   繁体   中英

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.

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.

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();"

How do I Solve the 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.

However I would refrain from using inline sql statements like above as this opens you up to SQL injection. Rather use paramaterised queries, stored procedures or LINQ to SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM