我正在尝试研究如何从文本字段或富文本字段中读取奇数 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();
}
}
根据您在下面的评论,我围绕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);