c# conversion bigint decimal
質問
I'm working on a c# application with a sql server 2005 database. 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 ?
if (dataReader.IsDBNull(0) == false) {
PLAYER.PLAYER_ID = dataReader.GetDecimal(0);
}
In my PLAYER object, PLAYER_ID is decimal type.
I use two different databases, therefore, the value that comes from the base can be bigint or decimal. If this is decimal thete's no problem, but if it's a bigint, i get an error.
解決
You should be able to use the GetFieldType method to determine the data type of the object.
他のヒント
You can use GetFieldType to determine the type
http://msdn.microsoft.com/en-us/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. Call it before you start reading rows and set a flag indicating which type this particular query returned.
Use 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.