【发布时间】:2017-05-11 08:53:06
【问题描述】:
我在将文本文件中的 NULL 值插入/批量插入 MSSQL 时遇到问题。 当用数字替换 NULL 值时,它可以正常工作。 2 列设置为 ALLOW NULLS,
PublicationCaption 和 PublicationNumber
这是文本文件的示例
1#DI#Dagens Industri#435#358#2016-10-19 2#DN#Dagens Nyheter#NULL#359#2016-10-19
我认为代码中的 foreach 循环存在一些问题,我需要添加一些内容才能使其正常工作。
这是我正在使用的代码
public static DataTable Publication()
{
DataTable dtPublication = new DataTable();
dtPublication.Columns.AddRange(new DataColumn[6] { new DataColumn("ID", System.Type.GetType("System.Int32")),
new DataColumn("PublicationCode", System.Type.GetType("System.String")),
new DataColumn("PublicationCaption",System.Type.GetType("System.String")),
new DataColumn("PublicationNumber", System.Type.GetType("System.Int32")),
new DataColumn("ProductNumber", System.Type.GetType("System.Int32")),
new DataColumn("CreatedDate", System.Type.GetType("System.DateTime")),
});
for (int i = 0; i < dtPublication.Columns.Count; i++)
{
dtPublication.Columns[i].AllowDBNull = true;
}
string txtData = File.ReadAllText(@"C:\Publication2.txt", System.Text.Encoding.Default);
foreach (string row in txtData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dtPublication.Rows.Add();
int i = 0;
foreach (string cell in row.Split('#'))
{
dtPublication.Rows[dtPublication.Rows.Count - 1][i] = cell;
i++;
}
}
}
return dtPublication;
}
调试时得到(输入字符串的格式不正确。无法存储在 PublicationNumber 列中。需要输入 Int32。)。
请我需要一些建议,帮助解决问题。 感谢您的宝贵时间。
【问题讨论】:
-
如果在字符串而不是 WORD NULL 中会有空格怎么办?喜欢 1#DI#Dagens Industri#435#358#2016-10-19 2#DN#Dagens Nyheter##359#2016-10-19
-
如果是 int 使用
int.Parse(cell)。一般来说,使用调试器。失败时cell的值是多少? -
@Whencesoever 它让我喜欢这样的错误(输入字符串的格式不正确。无法将 存储在 PublicationNumber 列中。需要输入 Int32)
-
@TimSchmelter 失败时单元格的值为“NULL”
-
@HenriThiesen:那你有答案了,如何将字符串
"NULL"翻译成数字?
标签: sql sql-server datatable insert null