C# MSSQL数据库查询SQL语句拼接
MSSQL数据库查询SQL语句拼接
string dbConStr = ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString; string sqlText = "SELECT * FROM UserInfo"; List<string> whileList = new List<string>(); List<SqlParameter> para = new List<SqlParameter>(); using (SqlConnection conn = new SqlConnection(dbConStr)) { using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); if (!string.IsNullOrEmpty(txtUserName.Text)) { string strSql = "userName like %@userName%"; whileList.Add(strSql); para.Add(cmd.Parameters.AddWithValue("@userName", "%"+txtUserName.Text+"%")); } if (!string.IsNullOrEmpty(txtAddress.Text)) { string strSql = "address like %@address%"; whileList.Add(strSql); SqlParameter p = cmd.Parameters.AddWithValue("@address", "%" + txtAddress.Text + "%"); para.Add(p); //SqlParameter para = new SqlParameter(); //para.ParameterName = "@address"; //para.Value = "%" + txtAddress + "%"; } if(whileList.Count > 0){ sqlText += " where " + string.Join(" and ", whileList); } lbResult.Text = sqlText; //textBox1.Text = sqlText; SqlParameter[] sqlpara = para.ToArray(); foreach (var item in sqlpara) { MessageBox.Show(item.ParameterName + " " + item.Value);
}
}