2011-01-18 46 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;