C#如何忽略无效列
我创建了以下C#如何忽略无效列,c#,sql-server,excel,sqlbulkcopy,C#,Sql Server,Excel,Sqlbulkcopy,我创建了以下SqlBulkCopy以将Excel中的数据插入SQL Server数据库。如果Excel中有无效列,例如second\u name而不是last\u name,我的程序将忽略该列,而其他列的数据将添加到数据库中 但是,使用下面的代码并没有发生这种情况。我收到一条错误消息 没有为一个或多个必需参数提供值 并且没有数据被插入到数据库中。有人能帮我解决这个问题吗?多谢各位 string myexceldataquery = "select person_id,first_nam
SqlBulkCopy
以将Excel中的数据插入SQL Server数据库。如果Excel中有无效列,例如second\u name
而不是last\u name
,我的程序将忽略该列,而其他列的数据将添加到数据库中
但是,使用下面的代码并没有发生这种情况。我收到一条错误消息
没有为一个或多个必需参数提供值
并且没有数据被插入到数据库中。有人能帮我解决这个问题吗?多谢各位
string myexceldataquery = "select person_id,first_name,last_name,gender from [Sheet1$]";
try
{
string sexcelconnectionstring = @"provider=microsoft.ACE.OLEDB.12.0;data source=" + excelFilePath +
";extended properties=" + "\"excel 12.0;hdr=yes;\"";
con.Open();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(con);
bulkcopy.DestinationTableName = "person";
while (dr.Read())
{
bulkcopy.ColumnMappings.Add("person_id", "person_id");
bulkcopy.ColumnMappings.Add("first_name", "first_name");
bulkcopy.ColumnMappings.Add("last_name", "last_name");
bulkcopy.ColumnMappings.Add("gender", "gender");
}
bulkcopy.WriteToServer(dr);
dr.Close();
oledbconn.Close();
MessageBox.Show("File imported into sql server.");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
这个问题使你前面的问题更有意义。因此,考虑到您上次询问过如何将列名放入组合框,即构建一个将“这些列名”映射到“那些列名”的UI,我很好奇为什么这段代码似乎根本不包含动态映射?为什么映射是硬编码的?为什么要将Colunmapping放在for循环中?。它应该在for循环之前。当结果超过一行时,您将添加重复的映射,这将产生错误。如果只有一行结果,代码将起作用。