在一个字符串替换所有单引号用两个单引号 [英] Replace all single quotes with two single quotes in a string

查看:130
本文介绍了在一个字符串替换所有单引号用两个单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#从数据库读取值。
中的查询字符串包含多个单引号 - 如:Esca'pes(正在从一个文本文件中读取查询字符串)

I am trying to read value from DB using c#. The query string contains multiple single quotes - such as: Esca'pes' (the query strings are being read from a text file)

所以,我想形成SQL查询之前全部更换为单引号用两个单引号。我的代码如下:

So, I wanted to replace all the single quotes with two single quotes before forming the SQL query. My code is as below:

if (name.Contains('\''))
{
    name = name.Replace('\'','\''');  
}



如何解决这一问题?

How to fix this?

推荐答案

使用字符串,而不是字符文字。

Use strings, not char literals.

name = name.Replace("'", "''");



然而,它听起来就像你串联SQL字符串在一起。这是一个巨大的不要,因为SQL注入的风险的现代应用设计规则。请使用SQL参数来代替。每一个现代DBMS平台支持他们,包括SQL Server和MySQL ADO.NET,甚至Access支持他们。

However it sounds like you're concatenating SQL strings together. This is a huge "DO NOT" rule in modern application design because of the risk of SQL injection. Please use SQL parameters instead. Every modern DBMS platform supports them, including ADO.NET with SQL Server and MySQL, even Access supports them.

这篇关于在一个字符串替换所有单引号用两个单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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