我将以下示例放在一起,以帮助您发现代码中可能存在的问题,以及它没有将 unicode 字符串保存到表中的原因。
本示例将 unicode 文本保存到 dbo.MyTable 表中,该表具有以下架构:
CREATE TABLE dbo.MyTable
(
MyColumn NVARCHAR(MAX)
)
这个逻辑会在dbo.MyTable 表中插入一条记录,其中包含来自textbox1.Text 的文本:
using (var cn = new SqlConnection("MyConnectionString"))
{
cn.Open();
using (var cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "INSERT dbo.MyTable (MyColumn) VALUES (@MyText)";
// Assuming textBox1 is your textbox...
cm.Parameters.Add(
new SqlParameter("@MyText", SqlDbType.NVarChar, -1) { Value = textBox1.Text }
);
cm.ExecuteNonQuery();
}
}
更新
根据您在下面的评论,我围绕SqlCommand 对您的代码进行了以下更改,以使用参数而不是字符串连接,我解释了为什么这是不好的here;下面的代码将按预期将您的 unicode 文本保存到您的表格中并且是安全的:
SqlCommand ins = new SqlCommand("UPDATE ProductTestSpecifications set Specification = @Specification where ProductID = @ProductID and TestID = @TestID", con);
// When building your SqlCommand, always use parameters if you are interacting with external input, this will protect you against SQL injection.
ins.Parameters.Add("@Specification", SqlDbType.NVarChar, -1).Value = myRichText.Text;
// Im assuming ProductID and TestID are System.Int32, if not, please change SqlDbType.Int to the appropriate type.
ins.Parameters.Add("@ProductID", SqlDbType.Int).Value = ProductID;
ins.Parameters.Add("@TestID", SqlDbType.Int).Value = TestID;
try
{
ins.ExecuteNonQuery();
}
catch (Exception ex)
{
result = ex.Message.ToString();
}