最近做个网站WebSite用是MySQL数据库但是当我用带参数sql语句进行模糊查询时发现MySQL没有识别我参数中内容经过了多次实验终于找到了答案拿出来和大家分享的前从网上找了好半天也没有找到答案呢可能是我知道论坛少的又少吧O(∩_∩)O哈哈~
不多说了详细如下:
public DataTable GetUserList( strParam1, strParam2, strParam3, strParam4)
{
StringBuilder sqlContent = StringBuilder;
ArrayList paramList = 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");
// 判断参数是否为空或""
(!String.IsNullOrEmpty(strParam1))
{
sqlContent.Append(" AND column1 LIKE @param1 ");
// 添加参数
paramList.Add( MySqlParameter("@param1", "%" + strParam1+ "%"));
}
(!String.IsNullOrEmpty(strParam2))
{
sqlContent.Append(" AND column2 LIKE @param2 ");
paramList.Add( MySqlParameter("@param2", "%" + strParam2 + "%"));
}
(!String.IsNullOrEmpty(strParam3))
{
sqlContent.Append(" AND column3 LIKE @param3 ");
paramList.Add( MySqlParameter("@param3", "%" + strParam3+ "%"));
}
(!String.IsNullOrEmpty(strParam4))
{
sqlContent.Append(" AND column4 LIKE @param4 ");
paramList.Add( MySqlParameter("@param4", "%" + strParam4+ "%"));
}
try
{
// 获取DB链接
dbConn.getConnection;
objDT = DataTable;
// DBUtil中查询思路方法
objDT = dbConn.executeQuery(sqlContent., paramList);
}
catch (Exception e)
{
throw e;
}
finally
{
// 关闭DB链接
dbConn.closeConnection;
}
objDT;
}
就是在动态添加参数这块出了问题搞了我好半天时间
正确写法:
sqlContent.Append(" AND column1 LIKE @param1 ");
// 添加参数
paramList.Add( MySqlParameter("@param1", "%" + strParam1+ "%"));
写法:
sqlContent.Append(" AND column1 LIKE '%@param1%' ");
// 添加参数
paramList.Add( MySqlParameter("@param1", strParam1));
最新评论