插入包含撇号的值时出错

时间:2013-05-07 13:33:48

标签: sql-server sql-server-2008

我是SQL Server 2008中text数据类型的新手

我创建了表:

CREATE TABLE sample(id int identity,name varchar(20),Yell_Your_self text) 

但我遇到插入问题

insert into sample values('ganesh','welcome to india')
insert into sample values('ganesh','welcome to india's largest temple')

第一个语句工作正常,但如何执行第二个语句?

5 个答案:

答案 0 :(得分:3)

试试这个 -

IF OBJECT_ID(N'dbo.sample') IS NOT NULL
   DROP TABLE dbo.[sample]

CREATE TABLE dbo.[sample]
(
      id INT IDENTITY(1,1) PRIMARY KEY
    , name VARCHAR(20)
    , Yell_Your_self VARCHAR(2000)
)

INSERT INTO dbo.[sample] 
VALUES
    ('ganesh', 'welcome to india'), 
    ('ganesh', 'welcome to india''s largest temple')

<强> UPDATE3:

public int get(string val1,string val2) 
{ 
    using(SqlConnection con = new SqlConnection(connectionString))
    {
        con.Open();

        int i = 0;

        using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.sample (name, Yell_Your_self) VALUES(@val1, @val2)", con))
        {
            cmd.Parameters.AddWithValue("@val1", val1);
            cmd.Parameters.AddWithValue("@val2", val2);
            i = cmd.ExecuteNonQuery();
        }

        con.Close();
        return i;
    }
}

答案 1 :(得分:1)

可能在印度的撇号中抛出错误

insert into sample values('ganesh','welcome to india''s largest temple')

答案 2 :(得分:1)

问题是你在字符串中有一个引号,而单引号是SQL中的字符串分隔符。

尝试:

INSERT INTO  sample VALUES ('ganesh','welcome to india''s largest temple')

答案 3 :(得分:0)

正如您已经意识到SQL面临的问题是逃避查询中的叛逆,我猜这是固定的。要回答关于如何从前端传递值的第二个问题,如C#,参数化查询是一种很好的方法。作为替代方案,你可以使用这个也涉及字符串操作来准备查询:

public int get(string val1,string val2) 
{ 
    string temp = string.Concat(val1,"," + val2); // concatenate all your params
    temp = temp.replace("'","''").replace(",","','");  // replace any single qoute with escaped single quote
    string s="insert into sample values('" + temp +  "')"; // append altered string in query
    SqlCommand cmd = new SqlCommand(s,con); 
    con.Open(); 
    int i = cmd.ExecuteNonQuery(); 
    con.Close(); 
    return i; 
}

希望它有所帮助!

答案 4 :(得分:0)

尝试传递动态值

insert into sample values(@name, N''' + @Yell_Your_self text + ''' )