簡體   English   中英

使用BindingSource的Filter屬性時如何正確轉義SQL

[英]How to properly escape SQL when using BindingSource's Filter property

我繼承了一個C#應用程序,該程序通過DataGridView列出了數據庫表中的數據。 還有一些文本字段用於過濾該數據。 這樣做是這樣的:

String listFilter = string.Format("City = '{0}'", this.toolStripSearch.Text);
this.customersBindingSource.Filter = listFilter;

toolStripSearch是用於按城市名稱搜索的文本字段。 問題是沒有SQL轉義。 在字段中添加引號會使應用程序崩潰。

在這里轉義SQL的正確方法是什么?

我認為BindingSource.Filter的“正確”方法是簡單地使用''來使單引號轉義,這聽起來很可怕。 例如,類似的東西。

String listFilter = string.Format("City = '{0}'", this.toolStripSearch.Text.Replace("'", "''")); 
this.customersBindingSource.Filter = listFilter;  

BindingSource綁定到數據庫中的數據時, Filter屬性使用與DataColumn表達式相同的語法。

http://msdn.microsoft.com/zh-CN/library/system.windows.forms.bindingsource.filter.aspx

您可以在此處找到有關所需語法的文檔:

http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx

從該鏈接:

字符串值應括在單引號內(並且字符串值中的每個單引號字符必須通過在其前面加上另一個單引號字符進行轉義)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM