问题描述
我已经在 c# 中创建了一个列表,现在我需要将该列表插入到 SQL Server 2008 中.这可能吗?请用一个简单的例子解释一下.
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.
推荐答案
这是一个简单的例子:
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();
}
}
}
这只是遍历列表中的所有项目并使用 ExecuteNonQuery
.
This just loops through all items in the list and executes one insert-command after the other with ExecuteNonQuery
.
编辑:如果您想知道将数组(或列表)插入 sql-server 的最有效方法,您绝对应该阅读以下内容:http://www.sommarskog.se/arrays-in-sql-2008.html
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.
这篇关于如何将 C sharp 中的列表插入 SQL Server 2008?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!