zoukankan      html  css  js  c++  java
  • 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);
    }
    }


      

  • 相关阅读:
    Machine Learning Basic Knowledge
    What is the reason that a likelihood function is not a pdf?
    MySql 增加字段 删除字段 修改字段名称 修改字段类型
    Manual install on Windows 7 with Apache and MySQL
    linux 解压命令大全[转]
    MVC2项目实践
    JSP显示新闻
    servlet应用
    login登录页面
    java web基础
  • 原文地址:https://www.cnblogs.com/nymz/p/14213501.html
Copyright © 2011-2022 走看看