C# and M$ SQL server co-operation

C float vs C# float

There is one thing worth pointing out.

I learned C language before Java and C#, C is not object-oriented and it’s datatypes are simple. C uses ‘float’ for decimal number and it’s arithmetic operation.

But for OO language Java and C#, ‘float’ has a different meaning. Because ‘float’ is used to represent a decimal number with many decimal places, just like double, it will lose some precision due to its data structure, if you are doing financial application with a few decimal places, you should use ‘decimal’ for exact precision. let’s look at an example.

float   input(program)    outcome(database)

C           1.1                      1.1                                            

C#         1.1                      1.100000012357486…

you can still get exact result by rounding up to 7th places. Double is 15th.

Database datatype vs .Net datatype

When working with database, this mapping will help you. (reference)

SQL type                  CLR type(sql server)               CLR type(.NET)

decimal                     SqlDecimal                             Decimal

float                          SqlDouble                               Double

Real                           SqlSingle                                 Single

Using Real+Single will have the effect simular to C, input 1.1 -> outcome 1.1

for example, working with SqlDataReader

Double d = reader.GetDouble(“SQL float type”)

but strangly there isn’t a GetSingle() method present, I use GetSqlSingle() instead, seems no problem. 

Null Handling

1. for Null value return from a query method

let’s take Guid as an example for Nullable.

you can use a Guid? for shorthand Nullable<Guid>, use it as a return type for your database query method.

and the use if(guid.HasValue) to determind where the query returns a value or not.

2. for null value inside the query method

use if(DBNull.Value.Equals(row[i])) to determind where a field in a row retrieve from the database is null.

These two are very handy method for handling database query. ^^


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s