1

I am trying to save ThinSpace (\u2009) to the database using ADO.NET classes, but instead I am getting "?" symbol in db in place of ThinSpace. String that I save to db in UTF8 format.

        var content = "This is a test";

        byte[] bytes = Encoding.Default.GetBytes(content);
        content = Encoding.UTF8.GetString(bytes);

        content = content.Replace(' ', '\u2009');

        using (var con = new SqlConnection(connStr))
        {
            con.Open();

            using (var com = new SqlCommand("insert into Messages values ('" + content + "')", con))
            {
                com.ExecuteNonQuery();
            }
        }

Result in DB

enter image description here

Polaris
  • 3,503
  • 10
  • 48
  • 61
  • 5
    have you tried `N'unicode text'` ? – Bizhan Jan 13 '19 at 14:51
  • just add big n(N) before the variable like so `"insert into Messages values (N'myValue')"` – styx Jan 13 '19 at 14:52
  • Already check "N" . this does not help – Polaris Jan 13 '19 at 15:00
  • Show us the new code that doesn't work – Larnu Jan 13 '19 at 15:01
  • 6
    Is the MessageBody field an `NVARCHAR` or `VARCHAR`? – Adam Jan 13 '19 at 15:06
  • 4
    Don't build SQL queries through string concatenation. Use parameterized queries. If you're not familiar with what SQL injection is, become familiar with it. – Daniel Mann Jan 13 '19 at 15:12
  • @Daniel Mann I know what is SQL injection. This code written just like example for Stackoverflow. This is not production code. :) – Polaris Jan 13 '19 at 18:30
  • Possible duplicate of [Ukrainian character change to question mark when insert to table](https://stackoverflow.com/questions/46196062/ukrainian-character-change-to-question-mark-when-insert-to-table) – Ilyes Jan 13 '19 at 19:28

2 Answers2

4

I believe you're trying to insert unicode into a VARCHAR column. The SQL below:

CREATE TABLE MessageBodies
(
     NVARCHARText NVARCHAR(255),
     VARCHARText VARCHAR(255)
);

DECLARE @Text AS NVARCHAR(MAX) = NCHAR(2009);

INSERT INTO UnicodeInserts
VALUES (@Text, @Text);

SELECT
    *
FROM 
    MessageBodies;

Returns:

enter image description here

We see that SQL Server Management Studio renders a ? for an unknown character in a VARCHAR column. You'll need to convert your column to an NVARCHAR for the text to render as expected.

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Adam
  • 3,592
  • 25
  • 29
2

may be this might help:

using (var com = new SqlCommand("insert into Messages values (@content)", con))
{
    var param = new SqlParameter("@content", SqlDbType.NVarChar);
    param.Value = content;
    com.Parameters.Add(param);
    com.ExecuteNonQuery();
}

your target column data type is needed to be NCHAR or NVARCHAR

Derviş Kayımbaşıoğlu
  • 26,360
  • 3
  • 47
  • 64