简体   繁体   English

C#转换Bigint十进制

[英]c# conversion bigint decimal

I'm working on ac# application with a sql server 2005 database. 我正在使用带有SQL Server 2005数据库的ac#应用程序。 what is the best way to convert to decimal a value brought to a datareader from a database, not knowing if the value that is coming from the base is a decimal or is a bigint ? 将不知道来自基数的值是十进制还是bigint而不是从数据库带到数据读取器的值转换为十进制的最佳方法是什么?

        if (dataReader.IsDBNull(0) == false) {
            PLAYER.PLAYER_ID = dataReader.GetDecimal(0);
        }

In my PLAYER object, PLAYER_ID is decimal type. 在我的PLAYER对象中,PLAYER_ID是十进制类型。

I use two different databases, therefore, the value that comes from the base can be bigint or decimal. 我使用两个不同的数据库,因此,来自基数的值可以是bigint或小数。 If this is decimal thete's no problem, but if it's a bigint, i get an error. 如果这是十进制thete没问题,但是如果它是bigint,我会报错。

您应该能够使用GetFieldType方法来确定对象的数据类型。

You can use GetFieldType to determine the type 您可以使用GetFieldType确定类型

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getfieldtype.aspx http://msdn.microsoft.com/zh-CN/library/system.data.sqlclient.sqldatareader.getfieldtype.aspx

Type type = dataReader.GetFieldType(0);

You can then use an appropriate reader method to read out the data. 然后,您可以使用适当的读取器方法来读取数据。

You probably want to avoid calling GetFieldType for every row. 您可能要避免为每一行调用GetFieldType。 Call it before you start reading rows and set a flag indicating which type this particular query returned. 在开始读取行并设置一个标志来指示此特定查询返回的类型之前,请先调用它。

Use Decimal.TryParse : 使用Decimal.TryParse

decimal tempID;

Decimal.TryParse(dataReader[0], out tempID);
PLAYER.PLAYER_ID = tempID;

It should convert the value to the decimal unless it's null. 除非为空,否则应将值转换为小数。 If it's null decimal will remain 0. 如果为null,则小数将保持为0。

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

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