简体   繁体   中英

SQL parametrized query. Adding unnecessary parameters

I'm using parametrized queries in a project to prevent SQL injection and I ran into an interesting scenario with query. I have a query that will some times have more parameters than others ie the where clause changes. Is there any difference, in performance or otherwise, between the two following code blocks? This code is inside an object so the "variables" are properties and both methods have access.

In this one I only add the parameters if the condition is met.

    public bool TestQuery()
    {
        SqlCommand command = new SqlCommand();
        string query = GetQuery(command);
        command.CommandText = query;
        //execute query and other stuff
    }
    private string GetQuery(SqlCommand command  )
    {
        StringBuilder sb = new StringBuilder("SELECT * FROM SomeTable WHERE Active = 1 ");
        if (idVariable != null)
        {
            sb.Append("AND id = @Id");
            command.Parameters.Add("@Id", SqlDbType.Int).Value = idVariable;
        }
        if (!string.IsNullOrEmpty(colorVariable))
        {
            sb.Append("AND Color = @Color");
            command.Parameters.Add("@Color", SqlDbType.NVarChar).Value = colorVariable;
        }
        if (!string.IsNullOrEmpty(sizeVariable))
        {
            sb.Append("AND Color = @Size");
            command.Parameters.Add("@Size", SqlDbType.NVarChar).Value = sizeVariable;
        }
        return sb.ToString();
    }

In this one I add all of the parameters every time and only add the where clause arguments if the condition is met.

    public bool TestQuery()
    {
        SqlCommand command = new SqlCommand(GetQuery());
        command.Parameters.Add("@Id", SqlDbType.Int).Value = idVariable;
        command.Parameters.Add("@Color", SqlDbType.NVarChar).Value = colorVariable;
        command.Parameters.Add("@Size", SqlDbType.NVarChar).Value = sizeVariable;
        //execute query and other stuff
    }
    private string GetQuery()
    {
        StringBuilder sb = new StringBuilder("SELECT * FROM SomeTable WHERE Active = 1 ");
        if (idVariable != null)
            sb.Append("AND id = @Id");
        if (!string.IsNullOrEmpty(colorVariable))
            sb.Append("AND Color = @Color");
        if (!string.IsNullOrEmpty(sizeVariable))
            sb.Append("AND Color = @Size");
        return sb.ToString();
    }

According to a test I did either of them will work. I personally prefer the second one because I feel it's cleaner and easier to read but I wonder if there is some performance/security reason I shouldn't be adding parameters that aren't used and are probably going to be null/empty string.

我想我会根据HABO的评论选择一个,因为在我的情况下,熊的答案并不真正有效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM