您的位置:首页 > 数据库 > MySQL

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

2008-11-26 00:49 543 查看
最近做一个网站,用的是MySQL数据库,但是当我用带参数的sql语句进行模糊查询时,发现MySQL没有识别我的参数中的内容。经过了多次实验,终于找到了答案,拿出来和大家分享。之前从网上找了好半天也没有找到答案呢,可能是我知道的论坛少之又少吧,O(∩_∩)O哈哈~
不多说了,详细如下:


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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: