这个asp.net代码不起作用

时间:2011-07-28 13:20:13

标签: .net asp.net vb.net .net-3.5 asp.net-3.5

任何人都知道为什么以下不起作用?

Dim strPhrase As String = "'%office%'"

objStringBuilder = New StringBuilder()

objSQLConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))

objSQLCommand = New SqlCommand("select col1, col2 from table1 where phrase like @phrase", objSQLConnection)

objSQLCommand.Parameters.Add("@phrase", SqlDbType.VarChar, 255).Value = strPhrase

objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()

While objSQLDataReader.Read()
objStringBuilder.Append(objSQLDataReader("col1") & " - " & objSQLDataReader("col2"))
End While

objSQLDataReader.Close()
objSQLCommand.Connection.Close()

return objStringBuilder.tostring()

如果我删除与phrase有关的任何内容,它会再次开始工作,即:

objStringBuilder = New StringBuilder()

objSQLConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))

objSQLCommand = New SqlCommand("select col1, col2 from table1", objSQLConnection)

objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()

While objSQLDataReader.Read()
objStringBuilder.Append(objSQLDataReader("col1") & " - " & objSQLDataReader("col2"))
End While

objSQLDataReader.Close()
objSQLCommand.Connection.Close()

return objStringBuilder.tostring()

我没有错误,它只返回一个空白字符串。

3 个答案:

答案 0 :(得分:4)

从搜索词组周围删除'',命令对象会处理所有这些内容。即。

Dim strPhrase As String = "%office%"

答案 1 :(得分:1)

你可以这样做

Dim strPhrase As String = "%office%"

并将以下行添加到连接字符串的末尾

allow user variables=true;

答案 2 :(得分:0)

像这样做

Dim strPhrase As String = "%office%"