现在的位置: 首页 > 综合 > 正文

SQL中单引号的转义

2013年02月26日 ⁄ 综合 ⁄ 共 699字 ⁄ 字号 评论关闭

很多时候,在数据库中某表某字符字段中,要存储的数据内容会含有单引号,比如下面:

string name = GetNameById(id);

string sql = string.Format("update cover_diagnose set name = '{0}' where id = 48951",name);

这样真的没问题吗?

假设name获取的字面值是这样的:O'neal;这条语句数据库执行会报错!

我们看看数据库端执行的sql语句内容是怎样的:     update cover_diagnose set name = 'O'neal' where id = 48951

很明显,数据库将字符 'O' 两端的单引号作为了字符的两个边界,而后面紧跟的那些代码则出现了编译的错误,无法执行.

因此,为了避免这种情况的发生,我们应该在后台代码中过滤这些字符串,获得正确的格式!

static void Main(string[] args)

{

    string name = GetNameById(id);

    name = StrFilter(name);

    string sql = string.Format("update cover_diagnose set name = '{0}' where id = 48951",name);

}

 

public static string StrFilter(string str)

{

    if (string.IsNullOrEmpty(str))

    {

        return null;

    }

    else

    {

        if (str.Contains("'"))

        {

            str = str.Replace("'", "''"); // 将单引号转义为双单引号 ''

            return str;

        }

        else

        {

            return str;

        }

    }

}

抱歉!评论已关闭.