症状:使用MySqlClient访问字段返回System.Byte[],但是使用ODBC访问时却不会有这种问题,返回正常字符。
分析:跟踪生成的内存中的值的确是 System.Byte[] 类型,然该类型数组中有字符的byte值。经过直接转化byte[]数据为string类型后,发现是正确的字符串。
解决:
1.发现数据库中数据表该字段的数据库类型为varchar(15) binary ,关键就是这个 "binary”,去掉就OK了。
2.select的时候 cast(name as varchar) name 也可以
今天补充一个方法:巨简单
3.在连接串中增加 Respect Binary Flags=false 的配置
参考资料如下:
Binary/Nonbinary Issues
There are certain situations where MySQL will return incorrect metadata about one or more columns. More specifically, the server will sometimes report that a column is binary when it is not and vice versa. In these situations, it becomes practically impossible for the connector to be able to correctly identify the correct metadat.
Some examples of situations that may return incorrect metadata are:
-
Execution of
SHOW PROCESSLIST
. Some of the columns will be returned as binary even though they only hold string data. -
When a temp table is used to process a resultset, some columns may be returned with incorrect binary flags.
-
Some server functions such
DATE_FORMAT
will incorrectly return the column as binary.
With the availability of BINARY
and VARBINARY
data types it is important that we respect the metadata returned by the sever. However, we are aware that some existing applications may break with this change so we are creating a connection string option to enable or disable it. By default, Connector/Net 5.1 will respect the binary flags returned by the server. This will mean that you may need to make small changes to your application to accomodate this change.
In the event that the changes required to your application would be too large, you can add 'respect binary flags=false' to your connection string. This will cause the connector to use the prior behavior. In a nutshell, that behavior was that any column that is marked as string, regardless of binary flags, will be returned as string. Only columns that are specifically marked as a BLOB
will be returned as BLOB
.