Walid Madrid Walid Madrid - 3 months ago 29
C# Question

Insert Double In Sql Server

I am using SQL Server 2008 and C#.
I'm declaring a variable of type

double
and i want to insert it in my database. I have this error:


data type conversion error varchar to numeric.


How could i insert a value of type double in SQL Server using C#?

This is the Code:

double variable = 13.2;

con.Open();
cmd=con.CreateCommand();
cmd.CommandText = "insert into etudient (IDetudient, [nom etudient], value) values('" + Convert.ToInt16( text_id.Text) + "' , '" + text_name.Text + "','" + variable + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("success");

Answer

Since, variable is of type double which is not a string, so you should be inserting the variable in this format:

" + variable + " and not '" + variable + "'

Further, your Insert query goes like this:

cmd.CommandText = "insert into etudient (IDetudient, [nom etudient], value)
    values('" + Convert.ToInt16( text_id.Text) + "' , '" + text_name.Text + "'," + variable + " )";

It is infact, recommended to use Parameterized Queries as it prevents SQL Injection Attacks.

using (var con = new SqlConnection(connectionString))
{
    con.Open();

    using (var cmd = new SqlCommand(
        @"INSERT INTO etudient (IDetudient, [nom etudient], value)
          VALUES (@ID, @Name, @Variable)", con))
    {
        cmd.Parameters.AddWithValue("@ID", text_id.Text);
        cmd.Parameters.AddWithValue("@Name", text_name.Text);
        cmd.Parameters.AddWithValue("@Variable", variable);
        cmd.ExecuteNonQuery();
    }
}