C# 将带有逗号的文本框转换为sql
我试图在sql中插入一个带有十进制值的文本框。 如果文本框包含点,那么它可以正常工作,但是如果有人使用逗号而不是点呢?我怎样才能同时抓住这两种情况 示例我想插入值1,9C# 将带有逗号的文本框转换为sql,c#,sql-server,sql-server-2008,C#,Sql Server,Sql Server 2008,我试图在sql中插入一个带有十进制值的文本框。 如果文本框包含点,那么它可以正常工作,但是如果有人使用逗号而不是点呢?我怎样才能同时抓住这两种情况 示例我想插入值1,9 con.Open(); SqlCommand cmd = new SqlCommand("Insert into inventory (price) values ('" + Convert.ToDecimal(textBox1.Text) + "')", con); cmd.ExecuteNonQuery(); con.Clo
con.Open();
SqlCommand cmd = new SqlCommand("Insert into inventory (price) values ('" + Convert.ToDecimal(textBox1.Text) + "')", con);
cmd.ExecuteNonQuery();
con.Close();
将数据类型varchar转换为float时出错。
我需要用户在文本框、点或逗号中输入的任何内容,以将其作为浮点值转换为sql如果您不知道用户是否将使用逗号或句点作为十进制分隔符(不知道其区域性),您可以尝试这两种方法。下面是一个参数化的示例
decimal decimalValue;
NumberFormatInfo formatWithPeriod = CultureInfo.InvariantCulture.NumberFormat;
if (!Decimal.TryParse(textBox.Text, NumberStyles.AllowDecimalPoint, formatWithPeriod, out decimalValue))
{
NumberFormatInfo formatWithComma = (NumberFormatInfo)formatWithPeriod.Clone();
formatWithComma.NumberDecimalSeparator = ",";
if (!Decimal.TryParse(textBox.Text, NumberStyles.AllowDecimalPoint, formatWithComma, out decimalValue))
{
//error here
return;
}
}
con.Open();
SqlCommand cmd = new SqlCommand("Insert into inventory (price) values (@price);", con);
var priceParameter = cmd.Parameters.Add("@price", SqlDbType.Decimal);
priceParameter.Precision = 18;
priceParameter.Scale = 2;
priceParameter.Value = decimalValue;
cmd.ExecuteNonQuery();
con.Close();
请参数化您的SQL!另外,我强烈建议使用
decimal
,而不是使用float
float
是一种不准确的数据类型,因此存在舍入等问题。对于文本框,为什么不将验证设置为停止数字和小数点以外的字符呢?首先,您的代码极易受到SQL注入攻击。您需要使用参数化查询。使用正确的区域性infoDmitry是否替换正确的方法?我的意思是,万一我在另一台有其他全球化设置的计算机上运行这个怎么办?这种方法适用于所有国家/地区的全球化设置吗?maccettura我是否也应该为此发送列的datadype?如果有人输入文本:1'),则替换将没有帮助;下表库存--代码>。