Asp.net中内联查询中的SQL查询问题

时间:2011-05-25 07:29:13

标签: asp.net sql sql-server sql-server-2005 sql-server-2008

我的sql表结构是这个

ID  DataName
1   Lipsum lorem 
3   lipsum's lorem

我在asp.net中的内联查询是

select * from table where DataName like 'lipsum's lorem'

它会出现以下错误:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 's'.
Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string ''.

我不想创建存储过程来防止这种情况,我希望使用内联查询来解决此问题。

5 个答案:

答案 0 :(得分:5)

你需要逃离'lipsum's lorem'中的'

'lipsum''s lorem'

但真正的解决方法是使用参数化查询,以防止SQL注入。

SqlCommand.CommandText = "SELECT * FROM Table WHERE DataName = @DataName";

在命令对象中为@DataName添加一个参数及其值。

SqlCommand.Parameters.AddWithValue("@DataName", Value);

答案 1 :(得分:1)

您的查询应该看起来像......

select * from table where DataName like 'lipsum''s lorem'

因为你需要逃离' to '以使其发挥作用。

有关详细信息,请查看此链接:http://blog.sqlauthority.com/2008/02/17/sql-server-how-to-escape-single-quotes-fix-error-105-unclosed-quotation-mark-after-the-character-string/

如果您使用Command Parameters,请查看以下链接:

答案 2 :(得分:0)

您应该用双引号替换单引号

String.replace("'", "''")

这意味着将搜索字符串放在字符串变量中,并用双引号

替换单引号
string str = "lipsum's lorem"
str.Replace("'", "''")

答案 3 :(得分:0)

ID DataName

1 Lipsum lorem

3 lipsum's lorem

从表中选择*,其中DataName就像'lipsum'的lorem'

从表中选择*,其中DataName ='lipsum'的lorem'

从表中选择*,其中DataName类似'lipsum%'(要选择两行)

答案 4 :(得分:0)

使用参数化查询。

var command = new SqlCommand()
    {
        CommandText = "SELECT * FROM [table] WHERE DataName = @dataName",
        Parameters = { { "@dataName", "lipsum's lorem" } }
    }
相关问题