2011-07-28 85 views
0

任何人都知道爲什麼以下不起作用?此asp.net代碼不起作用

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() 

我沒有得到任何錯誤,它只是返回一個空字符串。

回答

4

從搜索短語的周圍刪除'',命令對象處理所有這些。即

Dim strPhrase As String = "%office%" 
+0

+ 1,歡迎來到四圖俱樂部:D – Town

0

使它像這樣

Dim strPhrase As String = "%office%" 
+0

哎呦vb.net所以你不需要; – Mauro

+0

是嗎?不知道關於VB.NET :)。好雖然知道 – Rahul

1

你可以把它像這樣

Dim strPhrase As String = "%office%" 

,並添加波紋線連接字符串的結尾

allow user variables=true;