Reputation: 35
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");
Upvotes: 2
Views: 9514
Reputation: 4077
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();
}
}
Upvotes: 1
Reputation: 274
Erase the ' before and after variable...
If you put variable between ', you are saying it is text, that's why the error says it can't convert varchar to numeric.
Upvotes: 0