简体   繁体   English

如何在 C# 中从 MySQL 检索 tinyint 数据类型?

[英]How do I retrieve a data type of tinyint from MySQL in C#?

So in C# whenever I retrieved a tinyint from my MSSQL database I used the following cast.因此,在 C# 中,每当我从 MSSQL 数据库中检索 tinyint 时,我都会使用以下强制转换。

(int)(byte)reader["MyField"];

However, that cast doesn't seem to work in MySQL.但是,该演员表在 MySQL 中似乎不起作用。

What I have tried我试过的

(byte)reader["MyField"];

and just只是

(int)reader["MyField"];

Edit 1编辑 1

Exception例外

The specified cast is not valid.

Edit 2编辑 2

This is the data type.这是数据类型。

{Name = "SByte" FullName = "System.SByte"}

To determine the proper type, look at the value of要确定正确的类型,请查看的值

reader["MyField"].GetType()

in the debugger.在调试器中。

The problem is that due to casting and explicit operators:问题是由于强制转换和显式运算符:

(byte)objectExpression is is not the same as (byte)sbyteExpression . (byte)objectExpression(byte)sbyteExpression

The first is a [direct] cast which fails because the real object type is sbyte and not byte .第一个是[直接]铸造因为真正的对象类型是失败sbyte而不是byte The latter will perform a conversion that just happens to use a explicit operator (an "Explicit Conversion") with syntax that, unfortunately, still looks like a [direct] cast as per above.后者将执行恰好使用明确的运算符(“显式转换”)的语法,不幸的是,看起来还是像[直接]按上述转换 Here is an example of it failing sans-database:以下是 sans-database 失败的示例:

var obj = (object)(sbyte)0;
var i1 = (int)(sbyte)obj;  // okay: object (cast)-> sbyte (conversion)-> int
var i2 = (int)obj;         // fail: sbyte (cast)-> int (but sbyte is not int!)

Either use an (sbyte)objectExpression cast which is valid for the real object type, or Convert.ToInt32(objectExpression) which takes an object and does some magic to convert it to an int.要么使用对真实对象类型有效的(sbyte)objectExpression ,要么使用Convert.ToInt32(objectExpression)接受一个object并执行一些魔法转换为 int。 (Using Convert.ToByte could throw an exception on overflow.) (使用Convert.ToByte可能会在溢出时引发异常。)

Happy coding!快乐编码!

May I suggest to let the system work against itself?我可以建议让系统对自己工作吗? The DataReader class provides features for getting the correct type of value: DataReader 类提供了获取正确类型值的功能:

reader.GetInt32("id");
reader.GetByte("MyByteField");

This way the Reader provides you with the type you expect.通过这种方式,阅读器为您提供您期望的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM