特殊字符未保存在MS SQL中

Mar*_*tin 2 c# unicode encoding character-encoding sql-server-2008

这个捷克人物有一个小问题?.当从我的C#代码触发更新时,这个小bugger将无法保存到我的MS SQL表中.

如果我在SQL Management Studio中手动添加它,它将按原样保存,并且它也会在网站上正常显示.

但是从C#中保存它的过程只会u在表中保存的字符中结束,而不是?.

我的数据库字段是类型nvarchar,ntext并且数据库的排序规则是French_CI_AS.我正在使用MSSQL 2008.

码:

SqlCommand sqlcomLoggedIn = new SqlCommand("UPDATE Table SET id = 1, title = 'Title with ?' WHERE id = 1", sqlCon, sqlTrans);
int status = sqlcomLoggedIn.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Mar*_*ell 7

当前的问题是你没有使用unicode文字; 它必须是:

UPDATE Table SET id = 1, title = N'Title with ?' WHERE id = 1
Run Code Online (Sandbox Code Playgroud)

N很重要.

更大的问题是,你应该使用参数:

int id = 1;
string title = "Title with ?";
// ^^ probably coming from C# parameters

using(var sqlcomLoggedIn = new SqlCommand(
    "UPDATE Table SET title = @title WHERE id = @id", sqlCon, sqlTrans))
{
    sqlcomLoggedIn.Parameters.AddWithValue("id", id);
    sqlcomLoggedIn.Parameters.AddWithValue("title", title);
    int status = sqlcomLoggedIn.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)

然后问题消失了,你可以使用缓存的查询计划,避免sql注入