使用 BindingSource 的 Filter 属性时如何正确转义 SQL [英] How to properly escape SQL when using BindingSource's Filter property

查看:34
本文介绍了使用 BindingSource 的 Filter 属性时如何正确转义 SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个 C# 应用程序,它通过 DataGridView 列出数据库表中的数据.还有一些文本字段用于过滤该数据.这是这样做的:

I've inherited a C# application that lists data from a database table via a DataGridView. There are also a few text fields used to filter that data. This is done like so:

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

toolStripSearch 是用于按城市名称搜索的文本字段.问题是没有 SQL 转义.向字段添加引号会使应用程序崩溃.

toolStripSearch is a text field for searching by city name. The problem is that there is no SQL escaping. Adding a quote to the field crashes the app.

这里转义 SQL 的正确方法是什么?

What is the proper way of escaping SQL here?

推荐答案

我认为 BindingSource.Filter 的正确"方法是使用 '' 简单地转义单引号代码> 听起来很可怕.例如,类似的东西.

I think the 'correct' way for BindingSource.Filter is to simply escape the single quotes using '' as horrible as that sounds. E.g, something like.

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

BindingSource 绑定到数据库中的数据时,Filter 属性使用与 DataColumn 表达式相同的语法.

The Filter property uses the same syntax as DataColumn expressions when BindingSource is bound to data from a database.

http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter.aspx

您可以在此处找到有关所需语法的文档:

You can find documentation on the required syntax here:

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

来自该链接:

字符串值应该被括起来单引号内(和中的每个单引号字符字符串值必须被转义在它前面加上另一个单曲引号字符).

String values should be enclosed within single quotation marks (and each single quotation character in a string value has to be escaped by prepending it with another single quotation character).

这篇关于使用 BindingSource 的 Filter 属性时如何正确转义 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆