I have created a list in c#, now I need to insert the list into SQL Server 2008. Is this possible? please explain with a simple example.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Here's a simple example:
List<String> list = new List<String>() { "A", "B", "C" };
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand("INSERT INTO TABLE(Column)VALUES(@Column)", con))
{
cmd.Parameters.Add("@Column", SqlDbType.VarChar);
foreach (var value in list)
{
cmd.Parameters["@Column"].Value = value;
int rowsAffected = cmd.ExecuteNonQuery();
}
}
}
This just loops through all items in the list and executes one insert-command after the other with ExecuteNonQuery
.
Edit: If you want to know the most efficient ways to insert arrays(or lists) into sql-server, you should definitely read this: http://www.sommarskog.se/arrays-in-sql-2008.html
If you have a specific question later, you can come back and show what you've tried.