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,643
  • 10
  • 50
  • 61

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
  • 732,580
  • 175
  • 1,330
  • 1,459
Adam
  • 4,180
  • 2
  • 27
  • 31
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
  • 28,492
  • 4
  • 50
  • 72