Search code examples
c#sqlconcatenationoledb

using a variable in oledb command


What is the correct way to concatenate a variable when using the oledb command function in c# for a sql query. To apply some context im trying to make what a list box displays dependent on another selection made on a previous list box.This is what I've tried but doesn't work.

OleDbCommand projects = new OleDbCommand("SELECT *  FROM  Client_projects  
WHERE clients = " + (listBox1.SelectedItem.ToString()) , conn);


OleDbDataReader project = projects.ExecuteReader();
while (project.Read())

                {

                    // Add items from the query into the listbox

                    listBox2.Items.Add(project[1].ToString());


                }

Solution

  • String concatenation can lead to SQL Injection problems so you should not use it to build SQL. You should parameterize your query. So something like this...

    using (OleDbCommand projects = new OleDbCommand("SELECT * FROM Client_projects WHERE clients = ?", conn))
    {
        projects.Parameters.Add("?", OleDbType.VarChar).Value = listBox1.SelectedItem.ToString();
    
        OleDbDataReader project = projects.ExecuteReader();
    
        while (project.Read())
        {
            listBox2.Items.Add(project[1].ToString());
        }
    }
    

    OleDbCommand Parameters are set in the order they are specified in the SQL, so if you have more than one you must do them in order.

    using (OleDbCommand projects = new OleDbCommand("SELECT * FROM Client_projects WHERE clients = ? AND Date = ?", conn))
    {
        projects.Parameters.Add("?", OleDbType.VarChar).Value = listBox1.SelectedItem.ToString();
        projects.Parameters.Add("?", OleDbType.Date).Value = DateTime.Today;
    
        OleDbDataReader project = projects.ExecuteReader();
    
        while (project.Read())
        {
            listBox2.Items.Add(project[1].ToString());
        }
    }
    

    You are not using it but for other who might, SqlCommand uses named parameters...

    SELECT * FROM Client_projects WHERE clients = @Clients
    projects.Parameters.Add("@Clients", SqlDbType.VarChar).Value = listBox1.SelectedItem.ToString();