C#, SQL拼接查询

        private void NewMethod()
        {
            StringBuilder sqlStr = new StringBuilder();
            sqlStr.Append("select * from table1 ");
            List<string> wheres = new List<string>();
            List<SqlParameter> listParameters = new List<SqlParameter>();

            if (textBox1.Text.Trim().Length > 0)
            {
                wheres.Add(" txt1 like @txt1");
                listParameters.Add(new SqlParameter("@txt1", SqlDbType.NVarChar, 100) { Value = "%" + textBox1.Text.Trim() + "%" });
            }
            if (textBox2.Text.Trim().Length > 0)
            {
                wheres.Add(" txt2 like @txt2");
                listParameters.Add(new SqlParameter("@txt2", SqlDbType.NVarChar, 100) { Value = "%" + textBox1.Text.Trim() + "%" });
            }
            if (textBox3.Text.Trim().Length > 0)
            {
                wheres.Add(" txt3 like @txt3");
                listParameters.Add(new SqlParameter("@txt3", SqlDbType.NVarChar, 100) { Value = "%" + textBox1.Text.Trim() + "%" });
            }
            if (wheres.Count > 0)
            {
                sqlStr.Append(" where ");
                sqlStr.Append(string.Join(" and ", wheres));
            }
            string s = sqlStr.ToString();
            SqlParameter[] pms = listParameters.ToArray(); 
            //SqlHelper.ExecuteReader(s, pms);
        }

评论