【发布时间】:2015-05-26 02:19:13
【问题描述】:
我收到以下错误:
System.FormatException:输入字符串的格式不正确。
System.Exception:未知错误:INSERT 语句中的列数少于 VALUES 子句中指定的值。 VALUES 子句中的值数必须与 INSERT 语句中指定的列数匹配。
这很容易从 INSERT 语句中看出:
INSERT INTO [dbo].[Out] ([Tag],[Element],[PeriodID],[Pay],[Output Value],[User],[Source],[Date],[ElementID]) values (1014758,'System-Rate Total',153640061,'No',21,67,'z8310905','CalcEngine',getdate(),6859)
问题在于 应该是
上面的 INSERT 语句是在 C# 中创建的,如下所示:
commandText.AppendLine(string.Format("INSERT INTO [dbo].[Out] ([Tag],[Element],[PeriodID],[Pay],[Output Value],[User],[Source],[Date],[ElementID]) values ({0},'{1}',{2},'No',{3},'{4}','CalcEngine',getdate(),{5})", Tag, tx.ElementName, periodID, tx.Value, user, tx.ElementID));
所以它是 tx.Value 包含逗号而不是句点(句号)。
但是,这在我的笔记本电脑上运行良好,但在我们尝试安装解决方案的服务器上运行良好。我的笔记本电脑是 Windows 7,服务器是 Windows 8。这个解决方案使用 .Net Framework 4,并使用 VS 2010 创建它。
我尝试在控制面板中设置与笔记本电脑完全相同的服务器文化、语言等。 我什至在代码中添加了以下内容,以尝试阻止后续安装发生类似的事情(用于背景查看here):
// Creating a Global culture specific to our application.
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-ZA");
// Creating the DateTime Information specific to our application.
System.Globalization.DateTimeFormatInfo dateTimeInfo = new System.Globalization.DateTimeFormatInfo();
// Defining various date and time formats.
dateTimeInfo.LongDatePattern = "dd MMMM yyyy";
dateTimeInfo.ShortDatePattern = "dd-MMM-yyyy";
dateTimeInfo.LongTimePattern = "HH:mm:ss";
dateTimeInfo.ShortTimePattern = "HH:mm";
// Setting application wide date time format.
cultureInfo.DateTimeFormat = dateTimeInfo;
//Creating the Number Format Information specific to our application.
System.Globalization.NumberFormatInfo numberInfo = new System.Globalization.NumberFormatInfo();
numberInfo.NumberDecimalSeparator = ".";
// Setting application wide number format.
cultureInfo.NumberFormat = numberInfo;
// Assigning our custom Culture to the application.
CultureChanges.SetDefaultCulture(cultureInfo);
这是在 Windows 服务的 Main 方法中输入的,该方法启动另一个进程,最终执行上述 INSERT 语句。 (不确定我是否也需要将其添加到生成的进程中?)
无论如何,我不知道还能做什么或去哪里寻找这个错误。我想这一定与服务器的文化或不同设置有关。这个 21.67 的值可能是四舍五入的。
【问题讨论】:
-
为什么要将它保存为字符串根本?即使不是双精度,也先将其解析为双精度,然后插入 that 值并将列类型更改为映射的双精度类型。您应该始终为您的值选择正确的数据类型。阅读:sqlblog.com/blogs/aaron_bertrand/archive/2009/10/12/…
-
{3:##0.00}可以解决吗? ;)。 -
你可以将.Replace(',','.') 以字符串格式添加到你的变量中吗?
-
永远不要像这样连接 sql。使用参数化查询或更好的存储过程。
-
@Soner Gönül,@Zohar Peled,我同意你的看法。编写 SQL 肯定有更好的方法。但是,上述语句是在一个块中执行的数百个其他语句之一。在我们解决方案的大部分其余部分中,我们使用 LinqToSQL,但我们不能为每个插入都命中数据库。有成千上万的项目,每个项目都有数百个这样的插入。也就是说,让我们继续前进。为什么这可以在我的笔记本电脑上运行,而不是在服务器上运行?
标签: c# sql-server