C#中MySQL語(yǔ)句帶參數(shù)的模糊匹配問(wèn)題

字號(hào):

用的是MySQL數(shù)據(jù)庫(kù),但是當(dāng)我用帶參數(shù)的sql語(yǔ)句進(jìn)行模糊查詢時(shí),發(fā)現(xiàn)MySQL沒(méi)有識(shí)別我的參數(shù)中的內(nèi)容。經(jīng)過(guò)了多次實(shí)驗(yàn),終于找到了答案,拿出來(lái)和大家分享,不多說(shuō)了,詳細(xì)如下:
    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");
    // 判斷參數(shù)是否為空或""
    if (!String.IsNullOrEmpty(strParam1))
    {
    sqlContent.Append(" AND column1 LIKE @param1 ");
    // 添加參數(shù)
    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();
    // 調(diào)用DBUtil中查詢方法
    objDT = dbConn.executeQuery(sqlContent.ToString(), paramList);
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    // 關(guān)閉DB鏈接
    dbConn.closeConnection();
    }
    return objDT;
    }
    正確的寫法:
    sqlContent.Append(" AND column1 LIKE @param1 ");
    // 添加參數(shù)
    paramList.Add(new MySqlParameter("@param1", "%" + strParam1+ "%"));
    錯(cuò)誤的寫法:
    sqlContent.Append(" AND column1 LIKE '%@param1%' ");
    // 添加參數(shù)
    paramList.Add(new MySqlParameter("@param1", strParam1));