c#sql防注入模糊查询_SQL中利用LIKE实现模糊查询的功能
大家好,今日繼續(xù)講解《VBA數(shù)據(jù)庫解決方案》,今日講解的內(nèi)容是:利用ADO,實現(xiàn)模糊查詢。在上一講中,我們實現(xiàn)了利用ADO快速查找的功能,今日我們實現(xiàn)工作表中模糊查找的功能。我們?nèi)允抢蒙弦恢v的數(shù)據(jù)實現(xiàn), 在"兩表查詢數(shù)據(jù)"的工作表中有如下數(shù)據(jù):
我們注意到其中型號和生產(chǎn)廠家的數(shù)據(jù)有些是混的,這就給我們利用上講的內(nèi)容造成了不便,那么這個時候就要利用模糊查找了,如下的數(shù)據(jù):
我們需要在"兩表查詢數(shù)據(jù)"中A列+B列的內(nèi)容中找到上述表格中A列的對應(yīng)的型號,怎么處理呢?
我們看下面的代碼:
Sub mynzexcels_8()
'第39講,利用ADO,實現(xiàn)模糊查詢
Dim cnADO, rsADO As Object
Dim strPath, strTable, strSQL As String
Set cnADO = CreateObject("ADODB.Connection")
Sheets("Sheet5").Activate
'建立一個ADO的連接
strPath = ThisWorkbook.FullName
cnADO.Open "provider=Microsoft.ACE.OLEDB.12.0;extended properties='excel 8.0;hdr=no;imex=1';data source=" & strPath
i = 2
Do While Cells(i, 1) <> ""
Cells(i, 1).Select
Cells(i, 3) = "": Cells(i, 4) = "": Cells(i, 5) = ""
'這里只是提出F3,F3,F5的數(shù)據(jù)
strSQL = "select F3,F4,F5 from [兩表查詢數(shù)據(jù)$] where F1&F2 Like '%" & Cells(i, 1) & "%'"
Set rsADO = New ADODB.Recordset
rsADO.Open strSQL, cnADO, 1, 3
If rsADO.RecordCount <= 0 Then
MsgBox ("第" & i & "行數(shù)據(jù),沒有找到!")
Else
If rsADO.RecordCount = 1 Then
Cells(i, 3).CopyFromRecordset rsADO
Else
For TT = 1 To rsADO.RecordCount - 1
Rows(i + TT & ":" & i + TT).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(i + TT, 1) = Cells(i + TT - 1, 1): Cells(i + TT, 2) = Cells(i + TT - 1, 2)
Next
Cells(i, 3).CopyFromRecordset rsADO
i = i + TT - 1
End If
End If
rsADO.Close
Set rsADO = Nothing
i = i + 1
Loop
Set cnADO = Nothing
End Sub
代碼截圖:
代碼講解:
1 strSQL = "select F3,F4,F5 from [兩表查詢數(shù)據(jù)$] where F1&F2 Like '%" & Cells(i, 1) & "%'" 這句SQL語句就是實現(xiàn)了從"兩表查詢數(shù)據(jù)"的工作表數(shù)據(jù)中找到類似于Cells(i, 1)內(nèi)容的記錄,大家要注意的這種SQL語句的寫法,是like +% %的組合。
2 If rsADO.RecordCount = 1 Then
Cells(i, 3).CopyFromRecordset rsADO
如果僅為1條記錄,那么就直接拷貝。
3 For TT = 1 To rsADO.RecordCount - 1
Rows(i + TT & ":" & i + TT).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(i + TT, 1) = Cells(i + TT - 1, 1): Cells(i + TT, 2) = Cells(i + TT - 1, 2)
Next
Cells(i, 3).CopyFromRecordset rsADO
i = i + TT - 1
End If
如果是多條記錄,那么需要在原查詢記錄的下面插入行來填入查詢的結(jié)果,上述代碼就是完成了這個目的。
下面我們看代碼的運行結(jié)果:
今日內(nèi)容回向:
1 ADO如何實現(xiàn)模糊查找?
2 上述講解中的SQL語句是否明白呢?
總結(jié)
以上是生活随笔為你收集整理的c#sql防注入模糊查询_SQL中利用LIKE实现模糊查询的功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 关联索引_mysql中关于关
- 下一篇: c#读蓝牙数据_CSharp--Blue