本文介绍了C#帮助SqlBulkCopy类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请你指导我重写以插入IList< string>使用SqlBulkCopy类将数据转换为SQL Server表。 SQL Server表具有Identity列。
Hi, Could you please guide me re-write to insert IList<string> data into a SQL Server table using SqlBulkCopy class. The SQL Server table has Identity column.
public string toTbl(IList < string > records) {
const string connectionString = @ "Data Source=sqlserver;Initial Catalog=dbname;User Id=user;Password=password;";
try {
var studentData = from record in records
let srec = record.Split(',')
select new Student {
ID = srec[0],
Student = srec[1],
Grade = srec[2]
};
foreach(var i in studentData) {
using(SqlConnection sqlConnection = new SqlConnection(connectionString)) {
sqlConnection.Open();
using(SqlCommand cmd = new SqlCommand("INSERT INTO [Student] ([ID], [Student], [Grade]) VALUES (@ID, @Student, @Grade)", sqlConnection)) {
cmd.Parameters.AddWithValue("@ID", i.ID);
cmd.Parameters.AddWithValue("@Student", i.Student);
cmd.Parameters.AddWithValue("@Grade", i.Grade);
cmd.ExecuteNonQuery();
}
sqlConnection.Close();
}
}
} catch (Exception ex) {
message = ex.Message;
}
}
提前谢谢。
SQLEnthusiast
SQLEnthusiast
推荐答案
https://stackoverflow.com/questions/18100783/how-to-convert-a-list-into-data-table
只需记住省略Identity列,因为它将在插入时创建。
Just remember to omit the Identity column as it will be created upon insert.
这篇关于C#帮助SqlBulkCopy类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!