【发布时间】:2020-05-04 05:02:46
【问题描述】:
我正在尝试将表情符号插入我的 mysql。但它显示为???? -> “??”。
这是我到目前为止所做的。
我的 ASPX 页面
<meta charset="utf-8">
我的数据库表设置为:
utf8mb4_unicode_ci
我的数据库列设置为:
utf8mb4_unicode_ci
我的 MySQL 连接字符串:
server=mysql.server.com;uid=testuser;pwd=1234;database=testdb;convert zero datetime=True;charset=utf8mb4;
但是,如果我直接在 phpMyAdmin 中使用 sql 语句插入表情符号,它就可以完美地工作
INSERT INTO Notification (id, headline, notificationText, sentDate)
VALUES (null, 'test', '????', NOW())
但是当我尝试通过代码 (.NET C#) 插入时,它显示为“??”。
private void EmojiQueryTester()
{
string strSql = "INSERT INTO Notification (id, headline, notificationText, sentDate) " +
" VALUES (null, 'test', '????', NOW())";
string strConnectionString = "mysql.server.com;uid=testuser;pwd=1234;database=testdb;" +
"convert zero datetime=True;charset=utf8mb4";
using (var mySqlConnection = new MySqlConnection(strConnectionString))
{
mySqlConnection.Open();
var mySqlCommand = new MySqlCommand(strSql, mySqlConnection);
mySqlCommand.ExecuteNonQuery();
}
}
id = 27 由我的 .NET 代码插入,id = 28 由 phpMyAdmin 插入
我也尝试插入其他字符如下,但仍然没有运气:
U+1F601 | \xF0\x9F\x98\x81 |
显示创建表通知
CREATE TABLE `Notification` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`headline` varchar(255) COLLATE utf8mb4_bin NOT NULL,
`notificationText` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
`sentDate` date NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SELECT notificationText, HEX(notificationText) FROM Notification
这是我的编码查询
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'
打印出十六进制字符串
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
string notification = "????";
DBTool dbT = new DBTool();
dbT.tester(notification);
Response.Write(ConvertStringToHex(notification, Encoding.UTF8));
}
在浏览器中输出:F09F9880
dbo.HEX(通知):3F3F
dbo.notification: ??
所以浏览器中的输出基本上是笑脸的正确 HEX,但是在 dbo.HEX(notification) 中它转换为“3F3F”。所以基本上它是用 ASCII 写的,而不是它应该做的 UTF8。
【问题讨论】:
-
基于此,我认为是 C# 没有处理表情符号,但您可能已经知道了
-
是的,我知道。现在的问题是,如何解决它...... :D 我假设它的 MySqlCommand 没有以正确的格式或编码发送 strSql,问题是,为什么?`
-
每个表情符号通常都有一个代码。尝试使用代码而不是实际字符。
-
我尝试过使用“U+1F601”和“\xF0\x9F\x98\x81”,但没有成功......同样的问题......它变成了“??”
-
@naak2803 fix 是在 MySQL 中使用 UTF8 编码。例如
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin。与其在字段中对表情符号进行硬编码,不如将其作为参数传递
标签: c# mysql .net encoding emoji