用的是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));
责任编辑:小草