字符串值不正确:列的’\ xEF \ xBF \ xBD’

我有一个表,我需要处理各种角色。 字符包括Ø,®等。

我已将我的表设置为utf-8作为默认排序规则,所有列都使用表默认值,但是当我尝试插入这些字符时,我收到错误:字符串值不正确:’\ xEF \ xBF \ xBD’列’buyerName’at at第1行

我的连接字符串定义为

string mySqlConn = "server="+server+";user="+username+";database="+database+";port="+port+";password="+password+";charset=utf8;"; 

我不知道为什么我仍然看到错误。 我是否错过了.net连接器或我的MySQL设置?

– 编辑 –

我的(新)C#插入语句如下所示:

 MySqlCommand insert = new MySqlCommand( "INSERT INTO fulfilled_Shipments_Data " + "(amazonOrderId,merchantOrderId,shipmentId,shipmentItemId,"+ "amazonOrderItemId,merchantOrderItemId,purchaseDate,"+ ... VALUES (@amazonOrderId,@merchantOrderId,@shipmentId,@shipmentItemId,"+ "@amazonOrderItemId,@merchantOrderItemId,@purchaseDate,"+ "paymentsDate,shipmentDate,reportingDate,buyerEmail,buyerName,"+ ... insert.Parameters.AddWithValue("@amazonorderId",lines[0]); insert.Parameters.AddWithValue("@merchantOrderId",lines[1]); insert.Parameters.AddWithValue("@shipmentId",lines[2]); insert.Parameters.AddWithValue("@shipmentItemId",lines[3]); insert.Parameters.AddWithValue("@amazonOrderItemId",lines[4]); insert.Parameters.AddWithValue("@merchantOrderItemId",lines[5]); insert.Parameters.AddWithValue("@purchaseDate",lines[6]); insert.Parameters.AddWithValue("@paymentsDate",lines[7]); insert.ExecuteNonQuery(); 

假设这是使用参数化语句的正确方法,它仍然会给出错误

  "Incorrect string value: '\xEF\xBF\xBD' for column 'buyerName' at row 1" 

还有其他想法吗?

\xEF\xBF\xBD是unicode字符U+FFFD的UTF-8编码。 这是一个特殊的角色,也被称为“替换角色”。 来自维基百科页面的关于特殊unicode字符的引用:

替换字符 (通常是带有白色问号的黑色菱形)是在Specials表中的代码点U + FFFD的Unicode标准中找到的符号。 当系统无法将数据流解码为正确的符号时,它用于指示问题。 最常见的情况是字体不包含字符,但在数据无效且与任何字符不匹配时也会看到:

所以看起来您的数据源包含损坏的数据。 您也可能尝试使用错误的编码读取数据。 线条来自哪里?

如果您无法修复数据,并且您的输入确实包含无效字符,则可以删除替换字符:

 lines[n] = lines[n].Replace("\xFFFD", ""); 

永远,永远,永远创建这样的SQL语句。 这对SQL注入是开放的。

我正在添加这个作为答案,因为这是一个根本性的错误,你可能需要重写你的大部分程序。

这不是你如何为SQL语句提供参数,并且不值得任何人回答你的问题,因为你应该使用参数化查询,这可能也会解决你的问题。

Mattmanser是对的,从不通过在查询中直接连接参数来编写SQL查询。 参数化查询的一个示例是:

 string lastname = "Doe"; double height = 6.1; DateTime date = new DateTime(1978,4,18); var connection = new MySqlConnection(connStr); try { connection.Open(); var command = new MySqlCommand( "SELECT * FROM tblPerson WHERE LastName = @Name AND Height > @Height AND BirthDate < @BirthDate", connection); command.Parameters.AddWithValue("@Name", lastname); command.Parameters.AddWithValue("@Height", height); command.Parameters.AddWithValue("@Name", birthDate); MySqlDataReader reader = command.ExecuteReader(); ... } finally { connection.Close(); } 

对于那些使用PHP有类似问题的人,请尝试使用函数utf8_encode($string) 。 它只是工作!