2011-01-18 35 views
1

我正在开发一个必须支持多种语言的应用程序。为了解决特殊字符问题,我使用NVarhcar作为我的文本字段。所以我对文本字段的SQL查询是nVarchar和SqlParameter

insert into tbl_text(text)values(N'Chci tančit v oblasti') 

我的问题是把它放在SqlCommand的,至极是"insert into tbl_text(text)values([email protected])"。当然,它会在数据库表中保存"[email protected]"

你们知道吗?我正在使用C#和SQL 2008.

对不起,如果它很难理解我的问题。我的英语很差=/

+0

请问你甚至声明在所有的工作?当我尝试从SSMS中重新插入'N @ text'到'tbl_text.text`列时,我得到'Msg 207,Level 16,State 1,Line 4 无效的列名'N @ text'。 – binki 2014-07-16 14:44:42

回答

2

您应该参数化您的插入内容SqlParameters,它们允许您明确指定数据类型。 (同时它可以帮助您找出查询造成的SQL Server注入攻击)。

实施例:

SqlCommand cmd = new SqlCommand("insert into tbl_text (text) values(@MYTEXT)", myConnection); 
cmd.Parameters.Add(new SqlParameter("@MYTEXT", SqlDbType.NVarChar)).Value = "Chci tančit v"; 
cmd.ExecuteNonQuery(); 
+1

我会改变添加到AddWithValue的方法,因为添加已被弃用...我现在没有电脑,所以我不能给你确切的代码......但如果没有人回答,当我回家时,我一定会发布它:) – PedroC88 2011-01-18 23:32:49

+0

@ PredoC88你从哪里得到这些信息?刚刚检查http://msdn.microsoft.com/en-us/library/ht4eset1.aspx,它似乎不被弃用。 – BrokenGlass 2011-01-18 23:47:07

+0

@BrokenGlass他指的是[`SqlParameterCollection.Add(string,object)`](http://msdn.microsoft.com/en-us/library/9dd8zze1%28v=vs.110%29)这是一种方便方法。你应该真正使用`IDbCommand.CreateParameter()`而不是直接实例化`SqlParameter`并且从``SqlParameter``中删除`@`以减少对`System.Data.SqlClient`命名空间的依赖:-p。 – binki 2014-07-16 14:46:24

0

使用SQLParameters

下面是一个简单的例子:

var cmd = _dbCon.CreateCommand(); 
cmd.CommandText = 
    "insert into tbl_text (textfield) values(@textfield)"; 
cmd.Parameters.Add(new SQLParameter("@textfield", "Chci tančit v oblasti")); 
cmd.ExecuteScalar(); 
+0

你为什么要将问号更改为问号?您是否使用过时的20世纪80年代软件访问此网站? (我已经为你解决了这个问题。) – Timwi 2011-01-19 00:00:09

1

不要把“N”参数名称前使用字符串常量,表示它是一个Unicode字符串时,它才会被使用。所以,你的查询应该是:

insert into tbl_text(text) values (@text) 
4

添加(字符串对象)已被弃用,因为这个原因(从SQL Server团队的巴勃罗·卡斯特罗):

的问题是,无论是C#和 VB.NET编译器会为此代码公开非常奇怪的行为:

command.Parameters.Add(“@ p”,0);

你可能会想到这个使用 重载需要一个对象, 0值分配给它,而是 会选择那些需要 SqlDbType作为第二个参数过载!在 为了避免 添加(字符串,sqldbtype)之间的(和潜在 等)模糊性和添加(字符串, 对象),我们不推荐使用添加(字符串, 对象),并介绍 AddWithValue(字符串对象)。在 一般,有多个过载 其中辨别参数 类型是“对象”其中之一是一个 危险的事情要做。

0

下面是简单的例子

String filePath = @"D:\" + FileName; 
SqlCommand command = new SqlCommand(); 
command.Connection = connection; 
command.CommandText = 
    @"DECLARE @TraceId INT = (SELECT MAX(id) FROM sys.traces WITH (NOLOCK)) 
    SET @[email protected]+1 

    DECLARE @File NVARCHAR(256); 
    Set @File= (@filePath) 

    SET @[email protected]+1 --Var olandan bir fazla 

    DECLARE @MaxFileSize BIGINT = 1 /* max size of file as MegaByte*/ 
    DECLARE @FileCount INT = 1024 /* max file count for write*/ 

    exec sp_trace_create @traceid = @TraceId OUTPUT, 
            @options = 2, 
            @tracefile = @File, 
            @maxfilesize = @MaxFileSize, 
            @stoptime = NULL, 
            @filecount = @FileCount 

    SELECT @TraceId"; 

command.Parameters.Add(new SqlParameter("@filePath", SqlDbType.NVarChar)).Value = filePath;