在oledb命令

时间:2017-07-09 13:41:36

标签: c# sql concatenation oledb

在c#中使用c#中的oledb命令函数连接变量的正确方法是什么?要应用某些上下文我试图使列表框显示依赖于在前一个列表框中进行的另一个选择。这是我尝试过但不起作用。

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 个答案:

答案 0 :(得分:1)

字符串连接可能导致SQL注入问题,因此您不应该使用它来构建SQL。您应该参数化您的查询。所以像这样......

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参数按照在SQL中指定的顺序设置,因此如果您有多个参数,则必须按顺序执行。

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

您没有使用它,但对于其他可能的人,SqlCommand使用命名参数......

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