简体   繁体   English

在 c# 中插入单引号的异常

[英]exception on inserting single quote in c#

I am facing problem that.我正面临这个问题。 when I insert single quote in text field.当我在文本字段中插入单引号时。 on insertion it give exception of incorrect syntax near that particular field.在插入时,它会在该特定字段附近给出不正确的语法异常。 why is it?为什么? does single quote has special meaning to sqlserver?单引号对sqlserver有特殊意义吗?

what if user what to enter word like don't, it's, or sometime by mistake enter single quote in start then it give exception.如果用户输入什么,例如不要,它是什么,或者有时在开始时错误地输入单引号,那么它会给出异常。 is there any sol to handle this?有什么办法可以解决这个问题吗? if single quote has issue with sqlserver.. then how to deal it?如果单引号与 sqlserver 有问题.. 那么如何处理呢?

use SqlParameter instead of string concatenation使用SqlParameter而不是字符串连接

This kind of expressions is worst thing you can do in your code, because at first you will have problem with data type convertion, and second the doors of Sql Injection is opem for hackers这种表达式是您在代码中可以做的最糟糕的事情,因为首先您会遇到数据类型转换的问题,其次Sql 注入的门是黑客的操作

string someQuery = "Select * from SomeTbl Where SomeTbl.SomeColumn = '" + tbSomeBox.Text+ "'" ;

Instead of that just use this而不是只使用这个

string someQuery = "Select * from SomeTbl Where SomeTbl.SomeColumn = @param";
SqlCommand someCommand = new SqlCommand(someQuery, conn);
someCommand.AddParams("@param",tbSomeBox.Text);
...

Hope this helps希望这可以帮助

SQL Server strings are enclosed (typically) in single quotes, so a single quote within a string will result in an error if you don't escape it prior to it being INSERTed. SQL 服务器字符串(通常)用单引号括起来,因此如果在插入之前不对其进行转义,则字符串中的单引号将导致错误。

Single quotes simply need to be doubled up, so the string Will''s World would result in Will's World making it's way into the data.单引号只需加倍,因此字符串Will''s World将导致Will's World进入数据。

You will need to escape single quotes in SQL statements.您需要在 SQL 语句中转义单引号。

For example:例如:

'don''t'

In SqlServer, if you want to insert string with quotes, use quotes twice before and after the string.在 SqlServer 中,如果要插入带引号的字符串,请在字符串前后使用两次引号。 For example you want to insert 'Hello' , so insert it like '''Hello''' provided the field you want to insert in has string datatype like varchar etc.例如,您要插入'Hello' ,因此像'''Hello'''一样插入它,前提是您要插入的字段具有字符串数据类型,例如 varchar 等。

using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) { 
    con.Open(); 
    SqlCommand cmd = new SqlCommand(); 
    string expression = "(newsequentiali'd())"; 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.CommandText = "Your Stored Procedure"; 
    cmd.Parameters.Add("Your Parameter Name", 
                SqlDbType.VarChar).Value = expression;    
    cmd.Connection = con; 
    using (IDataReader dr = cmd.ExecuteReader()) 
    { 
        if (dr.Read()) 
        { 
        } 
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM