简体   繁体   中英

What are possible mistakes when connecting to SQL Server from C#?

I created a login form in C# connecting to a SQL Server 2008. And the data reader has an error. What should I do?

This is my project for finals

SqlConnection con = new SqlConnection(@"Data Source=SAMSUNG-PC\SQLEXPRESS;Initial Catalog=LOGIN;Integrated Security=True");//this is my sql pc server name
SqlDataReader dr;

SqlCommand cmd = new SqlCommand("Select * from tbl_log where Username ='" + textBox1.Text + "' and Password = '", con);

con.Open();

cmd.Parameters.AddWithValue("un", textBox1.Text);
cmd.Parameters.AddWithValue("pw", textBox2.Text);

dr = cmd.ExecuteReader();//this is my problem//

if (dr.HasRows)//and this//
{
    menu menu = new menu();
    menu.Show();
    this.Hide();
}
else
{
    MessageBox.Show("error");
}
con.Close();

I expect this output: if the password is correct go to new form and if the password is incorrect the message box will appear and say "error".

There is so much here that needs to be different. The big things are:

  • Correct query parameterization (avoid sql injection attacks)
  • Don't store passwords in plain text. Don't even do this in learning/practice code! Passwords should be one-way hashed (don't encrypt them, either) using a reputable algorithm.
  • using blocks to avoid leaving connections open if an exception is thrown, to avoid creating a denial-of-service situation to your database
  • Don't mix UI and database access. Really, even my code below ought to have two layers, where the auth code is in a separate class from the database code

Something like this is much better:

public static class DB 
{
    private static string ConnectionString = @"Data Source=SAMSUNG-PC\SQLEXPRESS;Initial Catalog=LOGIN;Integrated Security=True";

    public static bool ValidateUserCredentials(string username, string password)
    {
                        //PwdHash column should be Char(60) (not VarChar, not NChar)
        string sql = "Select PwdHash from tbl_log where Username = @User";

        string hash = "";
        using (var cn = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand(sql, cn))
        {
            //use actual column types and lengths from the database here
            // Do NOT use AddWithValue()!
            cmd.Parameters.Add("@User", SqlDbType.NVarChar, 20).Value = username;

            //keep the connection active for as brief a time as possible
            cn.Open();
            using (var rdr = cmd.ExecuteReader())
            {
                if (!rdr.Read()) return false;    
                hash = (string)rdr["PwdHash"];
            }
        }
        //based on this NuGet bcrypt library:
        //https://www.nuget.org/packages/BCrypt-Official/
        if (BCrypt.Net.BCrypt.Verify(password, hash)) return true;
        return false;
    }
}

Then you could use it from the user interface like this:

if (DB.ValidateUserCredentials(textBox1.Text, textBox2.Text))
{
    menu mu = new menu(); //can't give a variable the same name as it's type
    mu.Show();
    this.Hide();
}
else
{
    MessageBox.Show("error");
}

After all the correct remarks you've received from @Marc Gravell and more...

To refer specifically to your actual question, You should correct

SqlCommand cmd = new SqlCommand("Select * from tbl_log where Username ='" + textBox1.Text + "' and Password = '", con);

//Here you're trying to add parameters that don't exist    
cmd.Parameters.AddWithValue("un", textBox1.Text);
cmd.Parameters.AddWithValue("pw", textBox2.Text);

to

SqlCommand cmd = new SqlCommand("Select * from tbl_log where Username = @UserName and Password = @Password", con);

cmd.Parameters.AddWithValue("@UserName", textBox1.Text);
cmd.Parameters.AddWithValue("@Password", textBox2.Text);

Also to help you understand the error (and because it's a call to SQL), you should wrap the code with try-catch

And one last remark since you're a beginner... Use meaningful names. Try to avoid abbreviations, it's a bad habit.

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