我在尝试使用sql string +参数返回分页查询(SQL Server)时,PetaPoco面临一个非常奇怪的问题。 如果我只使用一个普通的SQL字符串,它会按预期返回结果集。如果我使用带有@ 0参数的字符串,则不返回resulset,即使我检查发出的SQL命令是正确的......
这是查询
Dim query As PetaPoco.Sql = New PetaPoco.Sql("SELECT DISTINCT UserName FROM EVA_Users WHERE UserName LIKE '@0%' ORDER BY UserName", filterSql)
Dim result As PetaPoco.Page(Of AutoCompleteUserName) = db.Page(Of AutoCompleteUserName)(1, rowsNumber, query)
这应该发出一个带有“filterSql”的命令作为@ 0的字符串参数非常简单,事实上,为该计数发出的SQL命令是:
SQL Command: SELECT COUNT(DISTINCT UserName) FROM EVA_Users WHERE UserName LIKE '@0%' -> @0 [String] = "tes"
对于pagin是:
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY UserName) peta_rn, peta_inner.* FROM (SELECT DISTINCT UserName FROM EVA_Users WHERE UserName LIKE '@0%' ) peta_inner) peta_paged WHERE peta_rn>@1 AND peta_rn<=@2 -> @0 [String] = "tes" -> @1 [Int64] = "0" -> @2 [Int64] = "10"
但是使用调试器我可以在这种情况下检查result.Items.Count = 0
如果我不使用参数但使用普通的sql字符串,它按预期工作:
Dim query As PetaPoco.Sql = New PetaPoco.Sql(String.Format("SELECT DISTINCT UserName FROM EVA_Users WHERE UserName LIKE '{0}%' ORDER BY UserName", filterSql))
我还在查询中直接尝试了带有SQL字符串+ Params的版本,但没有额外的好处,那样:
Dim result As PetaPoco.Page(Of AutoCompleteUserName) = db.Page(Of AutoCompleteUserName)(1, rowsNumber, query (with the @0 inside as a parameter), filterSql)
DTO AutoCompleteUser就是这个,来自一个包含多个字段的表格,我只用一个字段创建了这个字段:
Imports PetaPoco
Namespace Eva.Entities.Core
<TableName("EVA_Users")> _
<PrimaryKey("", autoIncrement:=False)> _
<ExplicitColumns> _
<Serializable()> _
Partial Public Class AutoCompleteUserName
Private mUserName As String
<Column> _
Public Property UserName As String
Get
Return mUserName
End Get
Set(value As String)
mUserName = value
End Set
End Property
End Class
End Namespace
任何提示?我想使用参数化版本来处理自己的sql注入方案。 提前致谢
答案 0 :(得分:1)
您需要将%
放在参数值中而不是sql中。该参数也不应该用单引号'
包围。
例如
Dim query As PetaPoco.Sql = New PetaPoco.Sql("SELECT DISTINCT UserName
FROM EVA_Users WHERE UserName LIKE @0 ORDER BY UserName", filterSql + "%")
Dim result As PetaPoco.Page(Of AutoCompleteUserName) =
db.Page(Of AutoCompleteUserName)(1, rowsNumber, query)