15

我有一张桌子需要处理各种字符。字符包括Ø、®等。

我已将表设置为 utf-8 作为默认排序规则,所有列都使用表默认值,但是当我尝试插入这些字符时出现错误:字符串值不正确:'buyerName' 列的'\xEF\xBF\xBD'第 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"

还有其他想法吗?

4

3 回答 3

32

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

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

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

If you can't fix the data, and your input indeed contains invalid characters, you could just remove the replacement characters:

lines[n] = lines[n].Replace("\xFFFD", "");
于 2012-06-22T18:56:41.350 回答
3

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();
}
于 2012-06-22T16:22:15.300 回答
0

To those who have a similar problem using PHP, try the function utf8_encode($string). It just works!

于 2015-08-25T14:04:05.617 回答