[英]Read unicode characters from text or richtext field
我将以下示例放在一起,以帮助您发现代码中可能存在的问题,以及未将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
周围的代码进行了以下更改,以使用参数而不是字符串连接,我在这里解释了为什么这样做很糟糕; 以下代码将按预期将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();
}
从使用RichTextBox的Text属性切换到Rtf属性。 它达到了我追求的结果...
谢谢大家
嗯,.NET从一开始就是unicode,所以它应该很简单。
确保您的数据库列排序规则也为Unicode(类型为nvarchar
或仅排序规则本身支持Unicode字符)。
当您提供代码示例时,它通常会有所帮助,以便更轻松地发现问题。
一种简单的方法是:
byte[] bytes = Encoding.Unicode.GetBytes(unicodeString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.