我试图从xml文件中读取值,然后使用bulkcopy将数据插入到我的数据库中.
class Customer { public int CustomerID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int ShowsNumber { get; set; } public int VisitNumber { get; set; } public int Cancellation { get; set; } }
我读了这样的数据:
List<Customer> customersList = ( from e in XDocument.Load(file).Root.Elements("cust") select new Customer { CustomerID = (int)e.Attribute("custid"),FirstName = (string)e.Attribute("fname"),LastName = (string)e.Attribute("lname"),ShowsNumber = (int)e.Attribute("count_noshow"),VisitNumber = (int)e.Attribute("count_resos"),Cancellation = (int)e.Attribute("count_cancel"),}).ToList();
然后我将customersList插入到这样的数据表中:
DataTable dataTable = getBasicDataTable(); for (int i = 0; i < customersList.Count; i++) { DaTarow daTarows = dataTable.NewRow(); daTarows[0] = customersList[i].CustomerID; daTarows[1] = customersList[i].FirstName; daTarows[2] = customersList[i].LastName; daTarows[3] = customersList[i].ShowsNumber; daTarows[4] = customersList[i].VisitNumber; daTarows[5] = customersList[i].Cancellation; dataTable.Rows.Add(daTarows); }
然后我将数据插入我的数据库,如下所示:
但我得到了这个例外
using (sqlBulkcopy sbc = new sqlBulkcopy(GetConnectionString())) { sbc.DestinationTableName = XMLReader.databaseTable; sbc.WritetoServer(dataTable); }
The given value of type String from the data source cannot be converted to type int of the specified target column.
如你所见,当我从我的xml中提取数据时,我已经使用了强制转换为int和字符串,它正在工作.那么为什么在插入数据库时我得到了那个例外?
注意
为了给你整个代码,这是getBasicDataTable函数
private DataTable getBasicDataTable() { DataTable dataTable = new DataTable(); dataTable.Clear(); dataTable.Columns.Add("customerID"); dataTable.Columns.Add("firstName"); dataTable.Columns.Add("lastName"); dataTable.Columns.Add("showsNumber"); dataTable.Columns.Add("visitNumber"); dataTable.Columns.Add("cancellation"); return dataTable; }
解决方法
在定义数据表时,需要将列指定为整数.像这样:-
dataTable.Columns.Add("customerID",typeof(int));
编辑:
我怀疑的另一个原因可能是你绑定数据表的方式(我的意思是列的顺序)与数据库表的绑定方式不匹配.原因是我认为默认映射不是Name to Name而不是sqlBulkcopy中的Index to Index.所以请重新检查您的数据库表顺序,它应该如下: –
CustomerID (INT) FirstName (VARCHAR\NVARCHAR) LastName (VARCHAR\NVARCHAR) ShowsNumber (INT) VisitNumber (INT) Cancellation (INT)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。