close


以下的寫法可避免這個問題:

SqlConnection cn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=TestDB01;Integrated Security=sspi;");

SqlCommand cmd = new SqlCommand();
cn.Open();

cmd.Connection = cn;
cmd.CommandText = "insert into [T_TestUnicode] (id, name , memo) values (@pId, @pName, @pMemo)";

///// OK
//cmd.Parameters.Add("@pId", SqlDbType.NVarChar).Value = "150";
//cmd.Parameters.Add("@pName", SqlDbType.NVarChar).Value = "简体中文";
//cmd.Parameters.Add("@pMemo", SqlDbType.NVarChar).Value = "简体中文";

///// OK. 不指定 DB type 也會成功
cmd.Parameters.Add(new SqlParameter("@pId", "160"));
cmd.Parameters.Add(new SqlParameter("@pName", "简体中文 2"));
cmd.Parameters.Add(new SqlParameter("@pMemo", "简体中文 Testing 456"));

cmd.ExecuteNonQuery();

 

直接組合SQL字串會有問題, 除非加上N前置字


//// Error, 簡體中文會變成問號
cmd.CommandText = "insert into [T_TestUnicode] (id, name , memo) values ('40','简体中文','简体中文 Testing 123')";

//// OK, but not a good way
cmd.CommandText = "insert into [T_TestUnicode] (id, name , memo) values ('41',N'简体中文',N'简体中文 Testing 123')";

數據庫的定序(Collation) = Chinese_Taiwan_Stroke_CI_AS

測試用的是 VS.Net 2013/.Net 4.5.1

從沒注意過這點, 因為早已習慣用 SqlParameter 來處理這類程式了, 一直都沒事

最近碰到某廠商開發的系統, 裡面的SQL幾乎都是用字串組合的, 才發現這問題

除了 SQL Injection 的問題外, 字串組合 SQL 的缺點再添一筆.

 

...不是什麼了不得的東西, 只是找個地方記下來.

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 花枝魚丸湯 的頭像
    花枝魚丸湯

    Dog's Life 2.0

    花枝魚丸湯 發表在 痞客邦 留言(0) 人氣()