Skip to content Skip to sidebar Skip to footer

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 depe

Solution 1:

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 (OleDbCommandprojects=newOleDbCommand("SELECT * FROM Client_projects WHERE clients = ?", conn))
{
    projects.Parameters.Add("?", OleDbType.VarChar).Value = listBox1.SelectedItem.ToString();

    OleDbDataReaderproject= 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 (OleDbCommandprojects=newOleDbCommand("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;

    OleDbDataReaderproject= 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();

Post a Comment for "Using A Variable In Oledb Command"