C#中MySQL语句带参数的模糊匹配问题

本文介绍了一种在MySQL中使用参数化SQL语句进行模糊查询的正确方法,并通过实例展示了如何避免常见的错误写法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 用的是MySQL数据库,但是当我用带参数的sql语句进行模糊查询时,发现MySQL没有识别我的参数中的内容。经过了多次实验,终于找到了答案,拿出来和大家分享,不多说了,详细如下:
  public DataTable GetUserList(string strParam1,string strParam2,string strParam3,string strParam4)
  {
  StringBuilder sqlContent = new StringBuilder();
  ArrayList paramList = new ArrayList();
  sqlContent.Append(" SELECT ");
  sqlContent.Append(" column1");
  sqlContent.Append(" ,column2");
  sqlContent.Append(" ,column3 ");
  sqlContent.Append(" ,column4 ");
  sqlContent.Append(" FROM ");
  sqlContent.Append(" tab_temp ");
  sqlContent.Append(" WHERE 1=1");
  // 判断参数是否为空或""
  if (!String.IsNullOrEmpty(strParam1))
  {
  sqlContent.Append(" AND column1 LIKE @param1 ");
  // 添加参数
  paramList.Add(new MySqlParameter("@param1", "%" + strParam1+ "%"));
  }
  if (!String.IsNullOrEmpty(strParam2))
  {
  sqlContent.Append(" AND column2 LIKE @param2 ");
  paramList.Add(new MySqlParameter("@param2", "%" + strParam2 + "%"));
  }
  if (!String.IsNullOrEmpty(strParam3))
  {
  sqlContent.Append(" AND column3 LIKE @param3 ");
  paramList.Add(new MySqlParameter("@param3", "%" + strParam3+ "%"));
  }
  if (!String.IsNullOrEmpty(strParam4))
  {
  sqlContent.Append(" AND column4 LIKE @param4 ");
  paramList.Add(new MySqlParameter("@param4", "%" + strParam4+ "%"));
  }
  try
  {
  // 获取DB链接
  dbConn.getConnection();
  objDT = new DataTable();
  // 调用DBUtil中查询方法
  objDT = dbConn.executeQuery(sqlContent.ToString(), paramList);
  }
  catch (Exception e)
  {
  throw e;
  }
  finally
  {
  // 关闭DB链接
  dbConn.closeConnection();
  }
  return objDT;
  }
  正确的写法:
  sqlContent.Append(" AND column1 LIKE @param1 ");
  // 添加参数
  paramList.Add(new MySqlParameter("@param1", "%" + strParam1+ "%"));
  错误的写法:
  sqlContent.Append(" AND column1 LIKE '%@param1%' ");
  // 添加参数
  paramList.Add(new MySqlParameter("@param1", strParam1));

转载于:https://www.cnblogs.com/supers/archive/2008/12/19/1358635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值