using a variable in oledb command

两盒软妹~` 提交于 2019-12-12 03:54:56

问题


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


                }

回答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 (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();


来源:https://stackoverflow.com/questions/44997046/using-a-variable-in-oledb-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!