Click here to Skip to main content
15,845,681 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How would I change this into a parameterized query? Its the code for the login for users to the system

C#
private void LoginButton_Click(object sender, EventArgs e)
        {

            SqlConnection sqlcon = new SqlConnection(@"Data Source=HP\SQLEXPRESS;Initial Catalog=Inventory;Integrated Security=True");
            string query = "Select * from Employees Where Username = '" + Username_txt.Text + "' and Password = '" + Password_txt.Text + "'";
            SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
            DataTable dtbl = new DataTable();
            sda.Fill(dtbl);

            if (dtbl.Rows.Count == 1)
            {
                Dashboard mainForm = new Dashboard();
                this.Hide();
                mainForm.Show();
            }
            else
            {
                LoginError.Visible = true;
            }
        }


What I have tried:

Re-writing code, but its still not working
Posted
Updated 4-Dec-17 11:26am
v3

Put a placeholder in your query for each parameter;
C#
string query = "SELECT * FROM Employees WHERE Username = @username AND Password = @password";

Then add the parameters to the query text as follows;
C#
// declare a datatable outside of your using statement
DataTable dtResults;
using(SqlConnection conn = new SqlConnection(@"Data Source=HP\SQLEXPRESS;Initial Catalog=Inventory;Integrated Security=True"))
{
    // create a SQL Command object    
    SqlCommand cmd = new SqlCommand(conn, query);
    // populate the parameters using either of the following methods
    cmd.Parameters.Add("@username", SqlDbType.Varchar);
    cmd.Parameters["@username"].Value = Username_txt.Text;
    cmd.Parameters.AddWithValue("@password", Password_txt.Text);
    // open the connection - should we wrapped in a try/catch block
    conn.Open();
    // create an adapter and fill the datatable with results
    SqlDataAdapter adap = new SqlDataAdapter(cmd);
    adap.Fill(dtResults);
}


MSDN is an excellent source of reference material, below is a link to the SqlCommand.Parameters property which you may find useful;SqlCommand.Parameters Property (System.Data.SqlClient)[^]

Kind Regards
 
Share this answer
 
an0ther is right about the parameterization, but there is another issue: never store passwords in plain text: Password Storage: How to do it.[^]
 
Share this answer
 
Comments
Richard Deeming 5-Dec-17 10:45am    
Some people never listen!
https://www.codeproject.com/Answers/1214540/Oledbexception-was-unhandled-Csharp-explanation-ne[^]

Still, at least the OP seems to finally be getting the message about SQLi. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900