繁体   English   中英

从文本或RTF字段读取Unicode字符

[英]Read unicode characters from text or richtext field

我正在尝试找出如何从文本字段或富文本字段中读取并存储奇数unicode字符到字符串中,然后在SQL数据库中进行更新。

我认为我已经整理了SQL方面的内容,但是我无法解决用户输入方面的问题。

我在用户输入的表单上有一个文本框或富文本框(都尝试过) 参考附件 进入字段,他们可以输入正确的输入,但是如何检索它以发送到SQL?

字符串变量只是将其转换为<104cfu / g。

有任何想法吗?

我将以下示例放在一起,以帮助您发现代码中可能存在的问题,以及未将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();
    }
}

UPDATE

根据下面的评论,我对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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM