INSERTing real or float data. Am I missing a key concept?

  • Thread starter Thread starter Ian R via DotNetMonster.com
  • Start date Start date
I

Ian R via DotNetMonster.com

I've only just started ADO.NET and I'm wondering if I'm missing a key concept
when trying to insert real data into my database.

The problem is that the CommandText property insists on converting the
decimal places of real data into commas. Take the following code for example:


*-------------------------------*
Dim SqlCommand As System.Data.SQLClient.SqlCommand
SqlCommand = New System.Data.SQLClient.SqlCommand
SqlCommand.Connection = SqlConnection

SqlCommand.CommandText = "INSERT INTO MyTable VALUES (" & 1.7 & ", " & 5.36 &
")"

SqlCommand.ExecuteNonQuery()
*-------------------------------*

The actual value of CommandText then becomes:
"INSERT INTO MyTable VALUES (1,7, 5,36)"

I'd be immensly grateful for any advice on how to use real numbers correctly.

Thanks in advance,

Ian
 
Hi Ian,

You should try using parameterized SQL.

i.e.

SqlCommand cmd = new SqlCommand("Insert Into MyTable Values(@param1,
@param2)";

cmd.Parameters.Add("@param1", 1.7);
cmd.Parameters.Add("@param2", 5.36);
cmd.ExecuteNonQuery();

Phil
 
SqlCommand.CommandText = "INSERT INTO MyTable VALUES (1.7,5.36)"

or, if you insist using concatenating,

SqlCommand.CommandText = "INSERT INTO MyTable VALUES (" & "1.7" & "," &
"5.36" & )"
 
Many thanks Phil, the key concept missing was the use of Parameters.

I can now stop shouting at the computer thanks to you :-)
Hi Ian,

You should try using parameterized SQL.

i.e.

SqlCommand cmd = new SqlCommand("Insert Into MyTable Values(@param1,
@param2)";

cmd.Parameters.Add("@param1", 1.7);
cmd.Parameters.Add("@param2", 5.36);
cmd.ExecuteNonQuery();

Phil
I've only just started ADO.NET and I'm wondering if I'm missing a key concept
when trying to insert real data into my database.
[quoted text clipped - 21 lines]
 
Always keep in mind that as soon as you "print" something this is subject to
a country dependent convention.

Here 1.7 in your national convention is printed as 1,7 resulting in this
error. You would have here to explicitely format the number.

The best solution would be to use parameters instead of building whole SQL
statements as strings. Else you'll have the same problem for dates for
example and even strings (you have to double '), etc...

By using parameters you don't transform this explicitely to text. You set
the parameter value to its "native" real, date or string value and that's
it... (additionaly it better protects from possible attacks that altering
the whole SQL by using the appropriate input to alter the final SQL
statement meaning).
 
Back
Top