使用webapi在sql数据库中以正确的格式保存Unicode数据

时间:2022-09-09 19:26:44

When I am trying to save Unicode data such as Chinese in my database it is saving as question marks ??????? in the sql database table.

当我试图在我的数据库中保存像中文这样的Unicode数据时,它会保存为问号???????在sql数据库表中。

    public  IHttpActionResult SaveSelections(UserPreference model)
    {
        var user = db.UserPreferences.FirstOrDefault(p => p.UserName == model.UserName);
        //var psellers= db.PSellers.ToArray();
        if (user == null)
        {
            try
            {
                db.UserPreferences.Add(model);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }
        else
        {
            try
            {
                user.AreaText = model.AreaText;
                user.RegionText = model.RegionText;                    

                db.SaveChanges();
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }

        }
        return Ok();
    }

1 个解决方案

#1


0  

Your database, as you said it in comment to your question, does not accept UTF8 but ASCII. What you have to do in order for database to accept unicode characters is run the following command:

正如您在评论中所说的那样,您的数据库不接受UTF8而是ASCII。要使数据库接受unicode字符,您需要执行的操作是运行以下命令:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_general_ci;

For more info see Database Character Set and Collation.

有关详细信息,请参阅数据库字符集和排序规则。

So basically, create new database and transfer current data to it. If you don't know how to do that, the answer is here.

所以基本上,创建新数据库并将当前数据传输给它。如果您不知道如何做到这一点,答案就在这里。

#1


0  

Your database, as you said it in comment to your question, does not accept UTF8 but ASCII. What you have to do in order for database to accept unicode characters is run the following command:

正如您在评论中所说的那样,您的数据库不接受UTF8而是ASCII。要使数据库接受unicode字符,您需要执行的操作是运行以下命令:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_general_ci;

For more info see Database Character Set and Collation.

有关详细信息,请参阅数据库字符集和排序规则。

So basically, create new database and transfer current data to it. If you don't know how to do that, the answer is here.

所以基本上,创建新数据库并将当前数据传输给它。如果您不知道如何做到这一点,答案就在这里。