下面是使用微软EnterpriseLibrary时的一段代码:
public DataTable GetContractReportData(string userName)
{
Database db = DatabaseFactory.CreateDatabase("SQLDBConnection");
string sql = @"SELECT
[UserName]
,[Birthday]
FROM [UserInfo]
WHERE 1 = 1 AND [UserName] LIKE '%@userName%' ";
DataTable dt = new DataTable();
using (DbCommand cmd = db.GetSqlStringCommand(sql))
{
db.AddInParameter(cmd, "@userName", DbType.String, userName);
dt = db.ExecuteDataSet(cmd).Tables[0];
}
return dt;
}
执行上面的代码后,返回空记录,可DB里明明是有数据的。经过仔细研究,发现LIKE语句的使用有问题,只要把上例中红色标识的代码替换为
WHERE 1 = 1 AND [UserName] LIKE '%' + @userName + ’%'";
程序执行后可以正常返回记录。