Reputation: 147
I have an double value in my insert request. I change the comma into a dot in this double value and have 12.5 instead of 12,5 when I create my MySqlCommand like in MySQL rules. But my string change my dot into a comma and send insert request with a comma and fired an exception. Why does MySqlCommand create a string with 12,5 and not 12.5?
string valueCapteur = "12,5";
valueCapteur = valueCapteur.Replace(',', '.');
double.TryParse(valueCapteur, NumberStyles.Any, CultureInfo.InvariantCulture, out double value);
MySqlCommand cmd = new MySqlCommand
{
Connection = cnn,
CommandText = "INSERT INTO `notification`(`Value`) VALUES (" + value + ");"
};
cmd.ExecuteNonQuery();
When I debug value = 12.5 but in my cmd.CommandText value = 12,5
Upvotes: 2
Views: 439
Reputation: 1062865
What you want are parameters:
using(MySqlCommand cmd = new MySqlCommand {
Connection = cnn,
CommandText = "INSERT INTO `notification`(`Value`) VALUES (@value);"
})
{
cmd.Parameters.AddWithValue("@value", value);
cmd.ExecuteNonQuery();
}
or with a tool like "Dapper":
conn.Execute("INSERT INTO `notification`(`Value`) VALUES (@value);", new { value });
One of the key points of parameters - in addition to avoiding SQL Injection - is that it avoids culture and formatting issues.
Upvotes: 3