用的是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));